#!   /usr/bin/python
#    coding: utf8

import sys
import time
import traceback
import os
import subprocess
import re

sys.path.append('.')
sys.path.append("pyts/")

##-------------------------------------------------------------------------------------------------
## Method to turn on the VME crate.
##-------------------------------------------------------------------------------------------------
## It calls the men-on script which sends the necessary SMTP commands to the ELMA crate to turn on
## power to the VME backplane.
##-------------------------------------------------------------------------------------------------
def men_on():
    print("Switching on the ELMA crate")
    subprocess.call("shell/men-on", shell=True, stdout=fnull, stderr=fnull)
    time.sleep(1)

##-------------------------------------------------------------------------------------------------
## Method to turn off the VME crate.
##-------------------------------------------------------------------------------------------------
## It calls the men-off script which sends the necessary SMTP commands to the ELMA crate to turn off
## power to the VME backplane.
##-------------------------------------------------------------------------------------------------
def men_off():
    print("Switching off the ELMA crate")
    subprocess.call("shell/men-off", shell=True, stdout=fnull, stderr=fnull)
    time.sleep(1)

##-------------------------------------------------------------------------------------------------
## Main "method" of PTS
##-------------------------------------------------------------------------------------------------
if __name__ == '__main__':

    print "\nHello and Welcome to the TTLBL PTS Run One Test!\n"

    fnull = open(os.devnull, "w")

    men_off()

    tsts = [1,2,3,4,5,6,7,8,10,12,13,14,15,16,17]
    tnum = input("--> Which test number: ")
    if tnum in tsts:
        pass
    else:
        print "Sorry that test can't be run"
        sys.exit(1)

    tcnt = input("--> How many times to run test: ")
    if tcnt < 0:
        print "Sorry bad run count"
        sys.exit(1)

    men_on()

    print "Loading FPGA bitstream..."
    ret = subprocess.call("cd boot; ./program", shell=True, stdout=fnull, stderr=fnull)
    time.sleep(1)

    if (ret != 0):
        print "ERROR: Bitstream download fail. Check JTAG connectivity."
    else:
        # Run JPTS
        cmd = "./jpts %d,%d" % (tnum, tcnt)
        subprocess.call(cmd, shell=True, stdout=sys.stdout, stderr=sys.stderr)

        cmd = "more log/*.log"
        subprocess.call(cmd, shell=True, stdout=sys.stdout, stderr=sys.stderr)

    men_off()

    msg = "--> To exit PTS Run One Test, type 'ok': "
    ok = raw_input(msg)
    while True:
        if ok.find("ok") != -1 or ok.find("OK") != -1:
            print "Exited PTS"
            time.sleep(1)
            sys.exit(1)
        else:
            ok = raw_input("--> To exit PTS Run One Test, type 'ok': ")
