#!/usr/bin/ardipython

import argparse
import platform
import shutil
import sys
#import pycurl
import os
from subprocess import call
#from StringIO import StringIO
import requests
import traceback
import xmltodict

def SetNSSM(nssmpath,drivername,property,value):
    cmd = "\"" + nssmpath + "\" set \"" + drivername + "\" " + property + " " + value
    call(cmd, shell=True)
    #print "Running - " + cmd

def WindowsUninstaller(driver,port):
    is64 = False
    if platform.machine().endswith('64'):
        is64 = True

    basepath = os.path.dirname(os.path.realpath(__file__))
    nssmpath = basepath
    if is64:
        nssmpath = nssmpath + "\\nssm\\win64"
    else:
        nssmpath = nssmpath + "\\nssm\\win32"

    nssmpath = nssmpath + "/nssm.exe"

    drivername = "ARDI " + driver.upper() + " Driver (" + str(port) + ")"

    cmd = "\"" + nssmpath + "\" stop \"" + drivername + "\""
    call(cmd, shell=True)

    cmd = "\"" + nssmpath + "\" remove \"" + drivername + "\" confirm"
    call(cmd, shell=True)
    #print "Running - " + cmd
    
def LinuxUninstaller(driver, portno):    
    print("Shutting Down Driver")
    cmd = "systemctl stop ardi-" + str(portno)
    call(cmd, shell=True)
    cmd = "systemctl disable ardi-" + str(portno)
    call(cmd, shell=True)

    print("Removing Service Definition")
    #cmd = "rm /etc/init.d/ardi-" + str(portno)
    cmd = "rm /etc/systemd/system/ardi-" + str(portno) + ".service"
    call(cmd, shell=True)
    
    print("Removing From Boot")
    #cmd = "update-rc.d ardi-" + str(portno) + " remove"
    cmd = "systemctl daemon-reload"
    call(cmd, shell=True)

def GetDriverDetails(remotehost,portno):    
    try:
        #buf = StringIO()
        
        url = 'http://' + remotehost + '/api/driverdetails?driver=' + str(portno)
        #print "Querying: " + url
        
        #c = pycurl.Curl()
        #c.setopt(c.URL, url)
        #try:
        #    c.setopt(c.WRITEDATA, buf)
        #except:
        #    c.setopt(c.WRITEFUNCTION, buf.write)
        #c.perform()
        #c.close()

        #print "Almost Done..."

        #s = buf.getvalue()
        web = requests.get(url,timeout=5)
        s = web.text

        result = xmltodict.parse(s)

        #print result
        try:
            print("Driver Name: " + result['driverinfo']['name'])
            print("Driver Type: " + result['driverinfo']['driver'])
            print("Driver Mode: " + result['driverinfo']['mode'])

            if (result['driverinfo']['mode'] == 'Live'):
                s = 'L'
            else:
                if (result['driverinfo']['mode'] == 'Event'):
                    s = 'E'
                else:
                    s = 'H'
            s = s + result['driverinfo']['driver']
        except:
            return ""
                            
        return s
    except:
        print("Failed To Get ARDI Driver Details")
        traceback.print_exc()
        return ""
    
parser = argparse.ArgumentParser(description="Manage ARDI Drivers")
parser.add_argument('port', help='The driver port/id number')
parser.add_argument('server',help='The URL of your ARDI instance')
parser.add_argument('--ifdriver',help='Only perform the action if the driver is of the matching type')
parser.add_argument('--driver',help='The type of driver (used to shut down Windows services)')


args = parser.parse_args()
    
#Override
server=args.server
port = int(args.port)
ifdriver = ""
if args.ifdriver is not None:
    ifdriver = args.ifdriver

#Get Driver Information
driver = GetDriverDetails(server,port)
if driver == "":
    if args.driver is not None:
        driver = 'L' + args.driver
    else:
        print("Driver Not Found On Specified ARDI Instance")
        sys.exit()
    
mode = "live"
if (driver[0] == 'H'):
    mode = "hist"
if (driver[0] == 'E'):
    mode = "event"

driver = driver[1:]

if ifdriver != "":
    if driver != ifdriver:
        print("Driver does not match given filter")
        sys.exit(0)
        
#Remove driver as a service...
   
if platform.system() == "Windows":
    WindowsUninstaller(driver,port)
else:
    LinuxUninstaller(driver,port)

basepath = os.path.dirname(os.path.abspath(__file__)) + "\\"
if basepath == "\\":
    basepath = ""


try:
    svpath = "/opt/ardi/supervisor.d/driver_" + sitename + "_" + str(port) + ".conf"
    if platform.system() == "Windows":
        svpath = os.path.abspath(basepath + "supervisor.d\\driver_" + sitename + "_" + str(port) + ".conf")

    try:
        os.remove(svpath)
    except:
        pass
except:
    pass

print("Removal Complete")
