#! /usr/bin/env python2.5

# No Copyright (-) 2008-2010 The Ampify Authors. This file is under the
# Public Domain license that can be found in the root LICENSE file.

"""
Usage: appengine <app-directory> <command> [options]

Available commands:

   run [dev_appserver.py options]

   deploy [appcfg.py options]

   get-logs [appcfg.py request_logs options]
"""

import sys

# ------------------------------------------------------------------------------
# exit if not python 2.5
# ------------------------------------------------------------------------------

if sys.version[:3] != '2.5':
    print "\n!! App Engine needs Python 2.5\n"
    sys.exit(1)

# ------------------------------------------------------------------------------
# imports
# ------------------------------------------------------------------------------

import subprocess

from cStringIO import StringIO
from os import mkdir
from os.path import abspath, dirname, exists, join as join_path, realpath
from shutil import rmtree
from time import time, sleep
from urllib import urlopen
from zipfile import ZipFile

# ------------------------------------------------------------------------------
# konfig
# ------------------------------------------------------------------------------

SDK_VERSION = "1.3.6"
SDK_VERSION_NAME = "1.3.6"

# ------------------------------------------------------------------------------
# some konstants
# ------------------------------------------------------------------------------

SCRIPT_ROOT = dirname(realpath(__file__))
MAIN_ROOT = dirname(SCRIPT_ROOT)

SDK_FILE = "google_appengine_%s.zip" % SDK_VERSION
SDK_PATH = "http://googleappengine.googlecode.com/files/" + SDK_FILE

OUR_SDK_PATH = join_path(MAIN_ROOT, '.appengine_python_sdk')
OUR_SDK_VERSION_FILE = join_path(OUR_SDK_PATH, 'VERSION')

# ------------------------------------------------------------------------------
# chek for app engine sdk
# ------------------------------------------------------------------------------

sdk_exists = None

if exists(OUR_SDK_VERSION_FILE):
    sdk_version = open(OUR_SDK_VERSION_FILE, 'rb').readline().split()
    sdk_version = sdk_version and sdk_version[-1] or ''
    if sdk_version == '"%s"' % SDK_VERSION_NAME:
        sdk_exists = True
    else:
        sdk_exists = False

if not sdk_exists:

    if sdk_exists is False:
        print
        print "# Removing Existing App Engine SDK %s" % sdk_version
        rmtree(OUR_SDK_PATH)

    error = None

    print
    print "# Downloading App Engine SDK..."

    try:
        sdk_file = StringIO(urlopen(SDK_PATH).read())
    except Exception, error:
        print
        print "!! Couldn't Download the SDK: %r" % error

    try:
        mkdir(OUR_SDK_PATH, 0777)
        sdk_zip = ZipFile(sdk_file)
        for name in sdk_zip.namelist():
            newname = name[17:]
            if not newname:
                continue
            if name.endswith('/'):
                mkdir(join_path(OUR_SDK_PATH, newname))
            else:
                newfile = open(join_path(OUR_SDK_PATH, newname), 'wb')
                newfile.write(sdk_zip.read(name))
                newfile.close()
    except Exception, error:
        print
        print "!! Couldn't Extract the SDK: %r" % error

    print

    if error:
        sys.exit(1)
    else:
        print "# App Engine SDK %s Successfully Installed." % SDK_VERSION
        print 

if __name__ == '__main__':

    argv = sys.argv[1:]

    if not len(argv) >= 2:
        print __doc__
        sys.exit()

    app_root = abspath(argv[0])
    updated_file_path = join_path(app_root, 'updated.py')

    command = argv[1]
    argv = argv[2:]

    if command in ['--help', '-h', 'help']:
        print __doc__
        sys.exit()

    if command == 'run':

        if not argv:
            argv = [app_root]

        subprocess.call(
            [sys.executable, join_path(OUR_SDK_PATH, 'dev_appserver.py')] + argv
        )

        sys.exit()

    if command == 'deploy':

        if not argv:
            argv = ['-v', 'update', app_root]
            updated_file = open(updated_file_path, 'wb')
            updated_file.write("APPLICATION_TIMESTAMP = %s\n" % time())
            updated_file.close()

        subprocess.call(
            [sys.executable, join_path(OUR_SDK_PATH, 'appcfg.py')] + argv
        )

        sys.exit()

    if command == 'get-logs':

        if argv:
            log_file = argv.pop(0)
        else:
            log_file = 'apache.log'
            if exists(log_file):
                print
                print "!! An apache.log file already exists in the directory"
                print
                sys.exit(1)

        subprocess.call(
            [sys.executable, join_path(OUR_SDK_PATH, 'appcfg.py')] +
            argv + ['request_logs', app_root, log_file]
        )

        sys.exit()

    print
    print "!! Unknown command: %s" % command
    print

# Local SDK Admin URLs:

# http://localhost:8080/_ah/login
# http://localhost:8080/_ah/admin
