#!/usr/bin/python
import sys, argparse, os
import sys
    
DEFAULT_SITE = 'donkey_simple_site'
try:
    import DonkeySimple
    import DonkeySimple.CmdInterface as dscmd
except ImportError:
    print 'Error Importing DonkeySimple, check its installed'
    sys.exit()

class Actions:
    def __init__(self, path):
        self.path = path
    
    def call_func(self, func_name):
        if hasattr(self, func_name):
            getattr(self, func_name)()
        else:
            raise Exception('Actions does not contain function "%s"' % func_name)
        
    def status(self):
        if self.path == DEFAULT_SITE: self.path = None
        dscmd.get_status(self.path)
        
    def runserver(self):
        if self.path == DEFAULT_SITE: self.path = None
        dscmd.runserver(self.path)
    
    def create(self):
        dscmd.create_ds(self.path)
        
    def generate(self):
        if self.path == DEFAULT_SITE: self.path = None
        dscmd.generate_site(self.path)
        
    def edituser(self):
        if self.path == DEFAULT_SITE: self.path = None
        dscmd.edituser(self.path)

parser = argparse.ArgumentParser(description="""Donkey Simple Controller.

Utility for building and controlling DonkeySimple websites 
DonkeySimple Version: %s
(https://github.com/samuelcolvin/donkey-simple).

  status - prints the status of the site you are currently in or the one specified by path.
  runserver - run the development server for this site.
  create - builds a new site at the specified path, default is "%s".
  generate - generates the site.
  edituser - edit a users password.
""" % (DonkeySimple.__version__, DEFAULT_SITE), formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument('action', metavar='action', choices=['status', 'runserver', 'create',  'generate', 'edituser'],
                   help='action to perform: status|runserver|create|generate|edituser')
parser.add_argument('path', metavar='site-path', nargs='?', default=DEFAULT_SITE,
                   help='Relative path of donkey simple site.')
    
args = parser.parse_args()

try:
    actions = Actions(args.path)
    actions.call_func(args.action)
except dscmd.KnownError, e:
    print 'Error: %s' % str(e)
except Exception, e:
    print 'Error: %s' % str(e)
    import traceback; traceback.print_exc()