#!/usr/bin/python

import sys
import getopt
import os, subprocess
import getpass
import time

def main(argv):  
    #get user input
    natip = check_blank_input("Enter target server nat ip: ")
    user = check_blank_input("Enter target server username: " )
    pw = getpass.getpass(prompt="Enter password for %s: " % user)
 
#temp
#    natip = "192.168.4.98"
#    user = "rack"
#    pw = "z8AO692o"
##
    v = "n"
    selectedmonitor = ""
    while v != 'y':
	print ""
        selectedmonitor = getMonitors(natip, user, pw)
        v = raw_input("You are going to failover %s.  Is this correct (y/n)?" % selectedmonitor)
	v = v[0].lower()

    #failover
    output = failover(natip, user, pw, selectedmonitor)
    #print output

  
    #loop until failedover or timeout
    start = time.time()
    timeout = 300 #seconds
    print "Please allow up to 5 minutes for failover to complete.  "
    while True:
        time.sleep(.5)
        log = runBash("tail -1 /var/log/DT/dtlog1.dtl")
        if ("Failover complete for " + selectedmonitor in log):
            print log
	    break
        secs_passed = time.time() - start
        if secs_passed >= timeout:
	    print "Failover is taking longer than expected.  Please contact the Disaster Recovery team at 7006135."
            break


def check_int_input(prompt,cnt):
    while True:
        try:
           int_input = int(raw_input(prompt))
	   if str(int_input).isdigit():
	        if int_input >= 1 and int_input < cnt:
        	    return int_input
	except ValueError:
	    print "Please enter the number of the source server to failover\n"


def check_blank_input(prompt):
    while True:
        try:
           int_input = raw_input(prompt)
           if int_input != "":
                return int_input
        except ValueError:
            print ""

 
def check_yn_input(prompt):
    while True:
        try:
           int_input = int(raw_input(prompt))
           if str(int_input).isdigit():
                return int_input
        except ValueError:
            print "Please enter the number of the source server to failover\n"



def failover(natip, user, pw, fosource):
    fooutput = runBash("DTCL login %s %s %s\\; failover \\\"%s\\\" on %s" % (natip, user, pw, fosource, natip))
    return fooutput

def getMonitors(natip, user, pw):

 # get available monitors
    monitors = runBash("DTCL login %s %s %s\\; monitor get %s;" % (natip, user, pw, natip))
    #parse output to capture available monitors
    monitornames=[]
    lines = monitors.split("\n")
    for l in lines:
	if('Unable' in l) or ('Ensure' in l):
	    print "\nPlease check the IP and credentials you entered and try again.\n"
	    sys.exit()
        elif('User access' not in l) and ('Monitor status' not in l) and ('Machine Name' not in l):
            l=l.strip()
            words = l.split(" ")
            monitornames.append(words[0])

    #Display monitor list to user and get monitor to failover
    cnt = 1
    for i in monitornames:
        print "%i:  %s" % (cnt, i)
        cnt = cnt + 1
    #mon = raw_input("Select the source server to failover: ")
    mon = check_int_input("Select the source server to failover: ", cnt)
    mon = int(mon)-1
    fosource = monitornames[mon]
    return fosource

def runBash(cmd):
    #print cmd
    process = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
    os.waitpid(process.pid, 0)
    return process.stdout.read().strip()

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