#!/usr/local/eenos/bin/python3 -Wd
'''
Eenos control panel  Web Admin Panel(WAP) command line utility
Copyright(c) eenos.com
License Required To use : EPL , https://eenos.com/epl
With a valid eenos commercial license, a.k.a EPL , you can use this software in a single server
Permission to use and modify under the terms of EPL . You an not allowed to resell or 
Distribute this software
'''
import os
import sys
import pwd
euid=pwd.getpwnam('eenos').pw_uid
sys.dont_write_bytecode = True
from datetime import datetime
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'settings')
def options():
    now = datetime.now()
    print('''Copyright(c) 2021-'''+str(now.year)+''', eenos.com
Eenos Web Admin Panel (WAP)   Utility
This tool will help you to run eensos web admin panel in dev mod 
Usage: /usr/local/eenos/wap/wapctl  <options> [values]
Command Groups:
Options:    
    -db, --dbsetup          -   To Setup the sqlite database
    -d, --dev               -   To Start Dev Mode on 0.0.0.0:8000    
    
    ''')

def parse_arguments(argus):
    length= len(argus)      
    choice={}
    if length == 1:
        cmd=argus[0]
        valid=['-db','--dbsetup','-d','--dev']
        if cmd in valid:
            if cmd == '-db' or cmd == '--debsetup':
                choice['migrate']='migrate'
                return choice
            elif cmd == '-d' or cmd =='--dev':
                choice['runserver']='runserver'
                return choice            
            else:
                print("Command not found")
                sys.exit(0)
        else:
            print("== Command options not found , please chose the following ==")
            options()
            sys.exit(0)
    else:
        print("== Command options not found , please chose the following ==")
        options()
        sys.exit(0)

def setupdb():
    db='/usr/local/eenos/wap/eenos-wap.db'
    try:
        from django.core.management import execute_from_command_line
        execute_from_command_line(['manage.py','migrate'])
        if os.path.isfile(db):
            os.chmod(db,0o640)
            os.chown(db,0,euid)
    except ImportError as exc:
        raise ImportError(
            "Couldn't import Django. Are you sure it's installed and "
            "available on your PYTHONPATH environment variable? Did you "
            "forget to activate a virtual environment?"
        ) from exc        
    
def runserver():
    try:
        from django.core.management import execute_from_command_line
        execute_from_command_line(['manage.py','runserver','0.0.0.0:8000'])        
    except ImportError as exc:
        raise ImportError(
            "Couldn't import Django. Are you sure it's installed and "
            "available on your PYTHONPATH environment variable? Did you "
            "forget to activate a virtual environment?"
        ) from exc        
    

def main():    
    try:
        from django.core.management import execute_from_command_line
    except ImportError as exc:
        raise ImportError(
            "Couldn't import Django. Are you sure it's installed and "
            "available on your PYTHONPATH environment variable? Did you "
            "forget to activate a virtual environment?"
        ) from exc
    execute_from_command_line(sys.argv)

if __name__ == '__main__':  
    if  os.geteuid()==0:
        if not sys.argv[1:]:
            options()
            sys.exit(0)
        argus = sys.argv[1:]
        result=parse_arguments(argus)
        if 'migrate' in result:
            setupdb() 
        elif 'runserver' in result:
            runserver()      
        else:
            main()
    else:
        print("You don't have privilege to run this tool")
        sys.exit(2)

