#!/usr/bin/python

import glob
import json
import os
import os.path
import requests
import sys
import time
import xml.dom.minidom
import yaml
import re

iterCount = 1
status = 0

try:
    cfgFile = sys.argv[1]
    if len(sys.argv) > 2:
        iterCount = int(sys.argv[2])
except Exception as e:
    print str(e)
    sys.exit(0)

with open( cfgFile, 'r' ) as config:
    config = yaml.safe_load( config )

auth = {
    'aaaUser': {
        'attributes': {
            'name': config['name'],
            'pwd': config['passwd']
            }
        }
    }

def refreshToken ():
    cookies = None
    status = 0
    while( status != 200 ):
        url = 'https://%s/api/aaaLogin.json' % config['host']
        while(1):
            try:
                r = requests.post( url, data=json.dumps(auth), timeout=1, verify=False )
                break;
            except Exception as e:
                print "timeout"
        status = r.status_code
        print r.text
        cookies = r.cookies
        time.sleep(1)
    return cookies

def runConfig( status, config ):
    cookies = refreshToken()
    tests = config['tests']
    status = 200

    for t in tests:
        type = t['type']
        url = 'https://%s/%s' % (config['host'],t['path'])
        file = t['file']

        if type=='file':
            file = t['file']
            with open(file,'r') as package:
                if( status==200) and ('wait' in t):
                    time.sleep( t['wait'] )
                else:
                    raw_input( 'Hit return to upload %s' % file )

                r = requests.post( url, 
                                   cookies=cookies,
                                   files={'file':package},verify=False  )
                result = xml.dom.minidom.parseString( r.text )
                status = r.status_code
                if( status == 200 ):
                    print "\033[32m"
                else:
                    print "\033[31m"
                print '++++++++ RESPONSE (%s) ++++++++' % file
                print result.toprettyxml()
                print '-------- RESPONSE (%s) --------' % file
                print status
                print "\033[0m"
        elif type=='delete':
                print t

                if( status==200) and ('wait' in t):
                    time.sleep( t['wait'] )
                else:
                    raw_input( 'Hit return to delete %s' % t['mo'] )

                url = 'http://%s/api/node/mo/uni/infra/mDev-%s.xml' % (config['host'],
                                                                       t['mo'])

                r = requests.delete( url,
                                     cookies=cookies,
                                     verify=False)
                result = xml.dom.minidom.parseString( r.text )
                status = r.status_code
                if( status == 200 ):
                    print "\033[32m"
                else:
                    print "\033[31m"
                print '++++++++ RESPONSE (%s) ++++++++' % t['mo']
                print result.toprettyxml()
                print '-------- RESPONSE (%s) --------' % t['mo']
                print status
                print "\033[0m"
        elif type=='xml':
            file = t['file']
            with open( file, 'r' ) as payload:
                data = payload.read()
                loopCount = 1

                # do parameter substitution
                if data.find("$1") != -1:
                    loopCount = iterCount

                for idx in range(0, loopCount):
                    if(status==200) and ('wait' in t):
                        time.sleep( t['wait'] )
                    else:
                        raw_input( 'Hit return to process %s' % file )

                    data1 = data
                    if loopCount > 1:
                        # first replace expressions
                        # currently we support expressions of the form (n+$1)
                        m = re.search("\((\d+)\+\$1\)", data) 
                        if m:
                            baseCount = int(m.groups()[0])
                            stringToReplace = "(" + str(baseCount) + "+$1)"
                            data1 = data.replace(stringToReplace, str(baseCount+ int(idx)))
                        # now replace the remaining parameters
                        data1 = data1.replace("$1", str(idx))
                    else:
                        data1 = data.replace("$1", str(1))
                    print '++++++++ REQUEST (%s) ++++++++' % file
                    print data1
                    print '-------- REQUEST (%s) --------' % file 
#                    url = 'https://%s/api/node/mo/.xml' % config['host']
                    url = 'https://%s/%s' % (config['host'],t['path'])
                    print "posting to URL", url
                    r = requests.post( url,
                                       cookies=cookies,
                                       data=data1,
                                       timeout=10000,
                                       verify=False )
                    result = xml.dom.minidom.parseString( r.text )
                    status = r.status_code
                    print '++++++++ RESPONSE (%s) ++++++++' % file
                    print result.toprettyxml()
                    print '-------- RESPONSE (%s) --------' % file
                    print status
                    if (idx+1) % 5 == 0:
                        cookies = refreshToken()
        else:
            print 'Unknown type:', type

runConfig( status, config )
