#!./python
# Make sure Zeus is running
# Take a list of HVs to work with
from testutil import *
import os

def help():
    print "Usage:"
    print "SANityCheck prepare hvs=<comma separated list of HVs> bs=<BACKUP_SERVER_IP> logs=<log directory> datastore=<datastore> number_of_vms=<NO_OF_VMS> workload_percentage=<PERCENTAGE>"
    print "SANityCheck run hvs=<comma separated list of HVs> bs=<BACKUP_SERVER_IP> logs=<log directory> datastore=<datastore> time=<BURNIN_TIME_IN_SECS>"
    print "SANityCheck backup hvs=<comma separated list of HVs> bs=<BACKUP_SERVER_IP> logs=<log directory> datastore=<datastore>"
    print "SANityCheck cleanup hvs=<comma separated list of HVs> bs=<BACKUP_SERVER_IP> logs=<log directory> datastore=<datastore>"
    print "SANityCheck summary logs=<log directory> testid=<TESTID>"

    sys.exit()

def ensureRequiredParamsPresent(dict, required_keys):
    for key in required_keys:
        if not dict.has_key(key):
            help()
            sys.exit()

if len(sys.argv) < 4:
    help()

command = sys.argv[1]
if command == 'summary':
    args = parseargs(sys.argv)
    ensureRequiredParamsPresent(args, ['logs', 'testid'])
    logs = args['logs'] 
    testid = args['testid']
    rc, out, err = runCommand(['grep', '-r', 'SUMMARY', '%s/%s' % (logs, testid)])
    for line in out.split('\n'):
        print ' '.join(line.split()[6:])
    sys.exit(0)
else:
    if len(sys.argv) < 5:
        help()

    args = parseargs(sys.argv)
    # Take a log path, or create a new one here in "logs"
    # Talk to one of the HVs get a list of datastores
    ensureRequiredParamsPresent(args, ['hvs', 'logs', 'datastore'])
    hvs = args['hvs']
    logs = args['logs']
    if not os.path.exists(logs):
        os.mkdir(logs)
    datastore = args['datastore']

if args.has_key('bs'):
    bs = args['bs']
else:
    bs = ''

# run a sanity sequence
if command == 'prepare':
    if len(sys.argv) < 7 or not args.has_key('number_of_vms') or not args.has_key('workload_percentage'):
        help() 
    number_of_vms = int(args['number_of_vms'])
    workload_percentage = int(args['workload_percentage'])

    # now modify the test files to these new numbers 
    cmd = ['sed', '-i', "s/0::VD::numberOfVMs [0-9]*/0::VD::numberOfVMs %d/g" % number_of_vms, 'test_config_files/vmlifecycle/create_vms.test']
    rc, out, err = runCommand(cmd)
    workload_vms = (number_of_vms*workload_percentage)/100
    cmd = ['sed', '-i', "s/0::VD::workloads [0-9]*/0::VD::workloads %d/g" % workload_vms, 'test_config_files/vmlifecycle/create_vms.test'] 
    rc, out, err = runCommand(cmd)

    if len(bs):
        rc, out, err = runCommand(['%s/testcontroller' % os.getcwd(), 'hvs=%s' % hvs, 'seqdir=%s/seqs' % os.getcwd(), 'outdir=%s' % logs, 'seq=sanity_prepare', 'datastore=%s' % datastore, 'deamonize=true', 'disablespacetest=true', 'bs=%s' % bs])
    else:
        rc, out, err = runCommand(['%s/testcontroller' % os.getcwd(), 'hvs=%s' % hvs, 'seqdir=%s/seqs' % os.getcwd(), 'outdir=%s' % logs, 'seq=sanity_prepare', 'datastore=%s' % datastore, 'deamonize=true', 'disablespacetest=true'])
    for line in out.split('\n'):
        if line.startswith('Test ID: '):
            print line
            break
elif command == 'run':
    if len(sys.argv) < 6 or not args.has_key('time'):
        help()
    runTimeInSeconds = int(args['time'])
    cmd = ['sed', '-i', "s/0::VD::runTimeInSeconds [0-9]*/0::VD::runTimeInSeconds %d/g" % runTimeInSeconds, 'test_config_files/vmlifecycle/burn_in.test']
    rc, out, err = runCommand(cmd)
    if len(bs):
        rc, out, err = runCommand(['%s/testcontroller' % os.getcwd(), 'hvs=%s' % hvs, 'seqdir=%s/seqs' % os.getcwd(), 'outdir=%s' % logs, 'seq=sanity_run', 'datastore=%s' % datastore, 'deamonize=true', 'disablespacetest=true', 'bs=%s' % bs])
    else:
        rc, out, err = runCommand(['%s/testcontroller' % os.getcwd(), 'hvs=%s' % hvs, 'seqdir=%s/seqs' % os.getcwd(), 'outdir=%s' % logs, 'seq=sanity_run', 'datastore=%s' % datastore, 'deamonize=true', 'disablespacetest=true'])
    for line in out.split('\n'):
        if line.startswith('Test ID: '):
            print line
            break
elif command == 'backup':
    if len(bs):
        rc, out, err = runCommand(['%s/testcontroller' % os.getcwd(), 'hvs=%s' % hvs, 'seqdir=%s/seqs' % os.getcwd(), 'outdir=%s' % logs, 'seq=sanity_backup', 'datastore=%s' % datastore, 'deamonize=true', 'disablespacetest=true', 'bs=%s' % bs])
    else:
        rc, out, err = runCommand(['%s/testcontroller' % os.getcwd(), 'hvs=%s' % hvs, 'seqdir=%s/seqs' % os.getcwd(), 'outdir=%s' % logs, 'seq=sanity_backup', 'datastore=%s' % datastore, 'deamonize=true', 'disablespacetest=true'])
    for line in out.split('\n'):
        if line.startswith('Test ID: '):
            print line
            break
elif command == 'cleanup':
    input = ''
    confirmed = False
    while not confirmed:
        input = raw_input("\nWARNING - this operation will destroy all VMs and remove all storage on this datastore zone, are you sure you want to go ahead with the cleanup? yes/no: ")
        if input == 'no':
            sys.exit()
        elif input == 'yes':
            confirmed = True
        else:
            print "\nInput error, please enter either yes or no ..."
            continue
       
    if len(bs): 
        rc, out, err = runCommand(['%s/testcontroller' % os.getcwd(), 'hvs=%s' % hvs, 'seqdir=%s/seqs' % os.getcwd(), 'outdir=%s' % logs, 'seq=sanity_cleanup', 'datastore=%s' % datastore, 'deamonize=true', 'disablespacetest=true', 'bs=%s' % bs])
    else:
        rc, out, err = runCommand(['%s/testcontroller' % os.getcwd(), 'hvs=%s' % hvs, 'seqdir=%s/seqs' % os.getcwd(), 'outdir=%s' % logs, 'seq=sanity_cleanup', 'datastore=%s' % datastore, 'deamonize=true', 'disablespacetest=true'])
    for line in out.split('\n'):
        if line.startswith('Test ID: '):
            print line
            break

#for line in out.split('\n'):
#    if line.find('SUMMARY - ') != -1:
#        # 19-03-2014-11:59:22 : Thread-2 : SUMMARY - NoOfExistingVMs 39
#        print line.split('SUMMARY - ')[1]

# extract relevant information from the test results like
# a) how many VMs were already present
# b) How many VMs were created
# c) How many workloads were created
# d) How long did the burn in test run
# e) How many of each of the operation types

