from flask import Flask, request
import json
import subprocess as sp
from postnote import postAlert


app = Flask('WebappReceiver')


def run_cmd(mycmd):
    print("Command: "+mycmd)
    myout = sp.check_output(mycmd, shell=True).decode("UTF-8")
    print(myout)
    return(myout)

def run_test(testname, instance, parameters):
    parameters = parameters+"\ntestname="+testname
    with open("/root/YSB_Minion/"+testname+"_"+instance+".txt","w") as fp:
        fp.write(parameters)
    mycmd = "/root/YSB_Minion/test.sh "+testname+" "+instance
    return(run_cmd(mycmd))

try:
    print("starting app")

    @app.route('/trigger', methods=['POST'])
    def trigger():
        myrequest = request.get_json()
        print("Data:\n")
        print(myrequest)
        myrequest["parameters"]=myrequest["parameters"].replace(" ","\n")
        myresult = run_test(myrequest["testname"], myrequest["instance"], myrequest["parameters"])
        #return('Posted: ' + str(myrequest))
        myret = "Triggered: "+str(myrequest)+"\n\n"+myresult
        return(myresult)



    @app.route('/runcommand', methods=['GET'])
    def runcmd():
        print("Your Command: ")
        mycmd=str(request.args['command'])
        print(mycmd)
        myout = sp.check_output(mycmd, shell=True)
        myout = myout.decode("UTF-8")
        print(myout)
        #myout = request.args['command']
        return ('action successful: ' + myout)


    @app.route('/', methods=['GET'])
    def button2():
        print("getting json data")
        return 'Hello world'

except Exception as e:
    # You will get a SlackApiError if "ok" is False
    assert e.response["ok"] is False
    assert e.response["error"]  # str like 'invalid_auth', 'channel_not_found'
    print("Got an error: {e.response['error']}")


if __name__ == '__main__':
    app.run('0.0.0.0', 8000, debug=False)

