#!/usr/bin/env python
# encoding: utf-8
import sys
import getopt
import traceback
import os

help_message = '''
The help message goes here.
'''


class Usage(Exception):
    def __init__(self, msg):
        self.msg = msg


def start ():
    """
    _start_
    starts the agent
    """
    print("Starting the agent")
    os.system('manage start-agent')

def stop ():
    """
    _stop_
    stops the agent
    """
    print("Stopping the agent")
    os.system('manage stop-agent')

def updateT0 ():
    """
    _updateT0_
    Updates the T0 version
    """
    print("Updating T0")
    os.system('pip uninstall -y T0')
    os.system('pip install T0')

def updateWMCore ():
    """
    _updateWMCore_
    Updates the T0 version
    """
    print("Updating WMCore")
    os.system('pip uninstall -y wmagent')
    os.system('pip install wmagent')

def resetCouch ():
    """
    _resetCouch_
    Cleans couchdb relevant directories and starts a new container
    """
    os.system('bash /data/tier0/00_pypi_reset_couch.sh')

def wipeT0ast (userInput='n'):
    """
    _wipeT0ast_
    Cleans T0AST database
    """
    if userInput == 'Y':
        os.system('bash /data/tier0/00_wipe_t0ast.sh')
    else:
        os.system('echo "Not wiping T0AST"')

def clearDeployment (userInput='n'):
    """
    _clearDeployment_
    Avoid re-deploying from scratch when unnecessary
    """
    if userInput == 'Y':
        resetCouch()
        wipeT0ast(userInput=userInput)
        os.system('rm -rf $WMA_CONFIG_DIR/.init*')
        os.system('rm -rf $WMA_INSTALL_DIR/*')
        os.system('rm -rf /data/tier0/admin/Specs/*')
        init()
    else:
        os.system('echo "Not performing anything"')
        os.system('sleep 2')

def init ():
    """
    _init_
    Runs the init.sh script
    """
    os.system('bash $WMA_DEPLOY_DIR/init.sh')

def addProcessingSite(site=None):
    """
    _resourceControl_
    Adds site to the resource control
    """
    command_1 = "manage execute-agent wmagent-resource-control --site-name={} --cms-name={} --pnn={} --ce-name={} --pending-slots=20000 --running-slots=20000 --plugin=SimpleCondorPlugin".format(site, site, site, site)
    command_2 = "manage execute-agent wmagent-resource-control --site-name={} --task-type=Processing --pending-slots=10000 --running-slots=10000".format(site)
def main(argv=None):
    if argv is None:
        argv = sys.argv

    try:
        try:
            opts, args = getopt.getopt(argv[1:], "h",
            ["help", "update-t0", "update-wmcore", "start-agent", "stop-agent", "clear-deployment", "resource-control" ])

        except getopt.error as msg:
            raise Usage(msg)

        # option processing
        for option, value in opts:
            if option in ("-h", "--help"):
                raise Usage(help_message)
            
            if option == "--update-t0":
                updateT0()

            if option == "--update-wmcore":
                updateWMCore()

            if option == "--start-agent":
                start()

            if option == "--stop-agent":
                stop()

            if option == "--clear-deployment":
                os.system('echo "This will clear T0AST database"')
                os.system('sleep 3')
                os.system('echo "This will remove /data/tier0/admin/Specs"')
                os.system('sleep 3')
                os.system('echo "This will reset couchdb container"')
                os.system('sleep 3')
                os.system('echo "Are you sure you wish to proceed? (Y/n)"')
                userInput = input()
                clearDeployment(userInput=userInput)

            if option == "--resource-control":
                site = value
                addProcessingSite(site)

    except Usage as err:
        print(sys.argv[0].split("/")[-1] + ": " + str(err.msg), file=sys.stderr)
        print("\t for help use --help", file=sys.stderr)
        return 2

if __name__ == "__main__":
    sys.exit(main())
