#!/usr/bin/env python

import os
import subprocess, shlex
from app import app, db
from flask_script import Manager, Shell, Command
from flask_migrate import Migrate, MigrateCommand

def make_shell_context():
    return dict(app=app,
                db=db, 
                User=User, 
                Role=Role, 
                Permission=Permission, 
                Deployment=Deployment)

migrate = Migrate(app, db)

manager = Manager(app)
manager.add_command('shell', Shell(make_context=make_shell_context))
manager.add_command('db', MigrateCommand)

@manager.command
def deploy():
    """Run deployment tasks."""
    from flask_migrate import upgrade
    from app.models import Role, User, Deployment, Product

    # migrate database to latest revision
    upgrade()

    # create user roles
    Role.insert_roles()
    Product.insert_products()

@manager.command
@manager.option('-r' '--restore_file', help='Restore from grid dump file')
def restore(restore_file):
    """ recreate db from grid export with python3 manage.py restore /path/grid.tar.bz2 """
    print(str(restore_file))
    #TODO
    from app.models import User
    db.session.add(User(email=str(user), password=str(password), confirmed=True, confirmed_on=datetime.datetime.now()))
    db.session.commit()

def run_scheduler():
    command_line = 'python3 /home/proxadmin/appserver/proxmaster-panel/schedulerd.py'
    args = shlex.split(command_line)
    p = subprocess.Popen(args)

@manager.command
def charge_deployments():
    from app.models import Product, Deployment, User
    Deployment.charge()

@manager.command
def charge_contracts():
    from app.models import Service, Contract, User
    Contract.charge()

@manager.command
def charge_domains():
    from app.models import Domain, User
    Domain.charge()

@manager.command
def runserver():
    print('Starting Scheduler...')
    #run_scheduler()

    print('Starting Flask...')
    app.run()

if __name__ == '__main__':
    manager.run()


