#!/usr/bin/python

import sys, os
from subprocess import Popen, call

usage = '''
Usage: wsgiblog.py [COMMAND]

Choose from the following commands: 

  Basic:

  install: install dependencies and create Administrator account
  run: fire-and-forget method of running the server
  stop: stop both the WSGI Blog and ZEO
  update: perform a Bazaar update of all source, recompile templates, and
          restart the server

  Advanced:

  start-blog: start the WSGI Blog server
  stop-blog: stop the WSGI Blog server
  start-storage: start the database server
  stop-storage: stop the database server
  shell: launch a Python shell to manage the database
  restart: restart the WSGI Blog server without performing updates
  update-ugly: update the Bazaar branch of the server, and recompile templates
           WARNING: changes don't apply until server restart
  templates-recompile: recompile the Cheetah templates under ./templates/
           WARNING: changes may not come into effect until server restart
  clear: clear data files
  deps: install dependencies

'''

args = []

def startblog():
    print('Starting WSGI Blog server...')
    call('nohup ./app.py &> blog.log', shell=True)

def startstorage():
    print('Starting ZEO server...') 
    call('./bin/zeoctl start', shell=True)

def stopblog():
    print('Stopping WSGI Blog server...')
    call('killall app.py', shell=True)

def stopstorage():
    print('Stopping ZEO server...')
    call('./bin/zeoctl stop', shell=True)

def stopall():
    stopblog()
    stopstorage()

def shellaccess():
    from storage import StorageFactory
    store = StorageFactory()
    from code import interact
    interact(banner='store = an open BlogStorage of the database',
             local={'store':store} )

def restart():
    stopblog()
    startblog()

def compiletemplates():
    print('Removing stale templates...')
    call('rm templates/*.py*', shell=True)
    print('Recompiling templates...')
    call('cheetah compile templates/*.tmpl', shell=True)

def updateugly():
    print('Performing Bazaar update...')
    Popen('bzr up', shell=True)

def clear():
    print('Ensuring ZEO server shutdown...')
    stopstorage()
    print('Deleting database...')
    call('rm ./var/Data.fs', shell=True)

def deps():
    print('Installing dependencies...')
    call('./dependencies.sh', shell=True)

def hasDeps():
    try:
	import app, blog, storage, views, security, util
        return True
    except ImportError as e:
        return False
    return True

def setupZEO():
    print('Setting up ZEO instance...')
    call('mkzeoinst2.6 .', shell=True)
    

#############

def install():
    if not hasDeps():
        global args
        if 'hasdeps' in args:
            raise(Exception('Dependencies could not be installed'))
            return
        deps()
        err = call([sys.executable, 'wsgiblog.py', 'install','hasdeps'])
        if err: sys.exit(1)
    setupZEO()
    print('Creating a new admin user...')
    username = raw_input('Username: ')
    from getpass import getpass
    password = getpass()
    nickname = raw_input('Nickname: ')
    homepage = raw_input('Website: ')
    from storage import storage_init, UserFactory
    from security import ADMIN
    startstorage()
    storage_init()
    UserFactory(username, nickname, password,
                ADMIN, homepage = homepage)
    stopstorage()
    print('Done. Run "./wsgiblog.py run" to launch the WSGI Blog!')


def wait():
    #call('sleep 3', shell=True)
    pass

def run():
    print('Ensuring servers aren\'t already running...')
    stopblog()
    stopstorage()
    compiletemplates()
    startstorage()
    print('Starting WSGI Blog...')
    startblog()
    wait()
    print('You\'re good to go!')

def updatepretty():
    stopblog()
    stopstorage()
    updateugly()
    run()

options = {
    'install': install,
    'run': run,
    'update': updatepretty,

    'start-blog': startblog,
    'stop-blog': stopblog,
    'start-storage': startstorage,
    'stop-storage': stopstorage,
    'stop': stopall,
    'shell': shellaccess,
    'restart': restart,
    'update-ugly': updateugly,
    'templates-recompile': compiletemplates,
    'clear': clear,
    'deps': deps,
    }

if __name__ == '__main__':
    version = sys.version_info[0] + sys.version_info[1]/10.
    if version<2.6 or version>=3.0:
        print('This version of WSGI Blog only works with Python 2.6-2.9.')
        print('Your version is: \n%s' % sys.version)
        sys.exit(0)

    global args
    args = sys.argv
    args = args + ['']

    curdir = os.path.dirname(os.path.realpath(__file__))
    os.chdir(curdir)

    option = args[1]
    if option in options:
        options[option]()
    else:
        print(usage)
        
    print('\nThank you for using fsufitch\'s WSGI Blog!')

