#To define a particular parameter, replace the 'parameterName' inside itsm.getParameter('parameterName') with that parameter's name

fromURL='https://nuticket.numsp.com/nuticket/download' ## Here mention the download url
company_id = itsm.getParameter('CID') #Provide the company ID

import os
import ctypes
from subprocess import PIPE, Popen
import ctypes
import urllib
import subprocess
import json
import ssl

class disable_file_system_redirection:
    _disable = ctypes.windll.kernel32.Wow64DisableWow64FsRedirection
    _revert = ctypes.windll.kernel32.Wow64RevertWow64FsRedirection
    def __enter__(self):
        self.old_value = ctypes.c_long()
        self.success = self._disable(ctypes.byref(self.old_value))
    def __exit__(self, type, value, traceback):
        if self.success:
            self._revert(self.old_value)

def downloadFile(DownTo, fromURL):
    try:
        with open(DownTo, 'wb') as f:
            try:
                context = ssl._create_unverified_context()
                f.write(urllib.urlopen(fromURL,context=context).read())
            except:
                f.write(urllib.urlopen(fromURL).read())
        if os.path.isfile(DownTo):
            return '{} - {}KB'.format(DownTo, os.path.getsize(DownTo)/1000)
		
    except:
        return 'Please Check URL or Download Path!'

Down_path=os.environ['PROGRAMDATA']
fileName = 'NuTicket.exe'
DownTo = os.path.join(Down_path, fileName)
local_path = os.getenv('LOCALAPPDATA')
install_path=os.path.join(local_path,'NuTicket')

def install():
    try:
        print downloadFile(DownTo, fromURL )

        if os.path.exists(DownTo):
            ec='%s "/S"'%DownTo
            print ec
            OBJ = Popen(ec, shell = True, stdout = PIPE, stderr = PIPE)
            out, err = OBJ.communicate()
            RET = OBJ.returncode
            if RET == 0:
                return "NuTicket is installed"
            else:
                return "NuTicket is not installed"
        else:
            print "Please check the path"
    except Exception as err :
        print err
print install_path
try:
    if not os.path.exists(install_path):
        print install()
    else:
        if not os.listdir(install_path):
            print install()
        else:
            print "NuTicket Already installed"
        
except Exception as err :
    print err
	
if os.path.exists(DownTo):
    os.remove(DownTo)

if not os.path.exists(install_path+"\\config.json"):
    data ={
      "CID": company_id
    }
    json_data = json.dumps(data, indent = 4)
    with open(install_path+"\\config.json", "w") as outfile: 
        outfile.write(json_data)
	
import _winreg
Key= r"Software\Microsoft\Windows\CurrentVersion\Run" ## Here give the registry Key path. STRING
Sub_Key= "NuTicket" ## Here give the sub Key of the registry. STRING
Field= _winreg.REG_SZ ##Here give the field of it
exe_path = os.path.join(install_path,'NuTicket.exe')
value = '"%s" /background'%(exe_path)  ##Mention the value 

from _winreg import *
try:
    Key=r"Software\Microsoft\Windows\CurrentVersion\Run"
    if not os.path.exists(Key):
        key = _winreg.CreateKey(HKEY_CURRENT_USER,Key)
    Registrykey= OpenKey(HKEY_CURRENT_USER,Key, 0,KEY_WRITE)
    _winreg.SetValueEx(Registrykey,Sub_Key,0,Field,value)
    CloseKey(Registrykey)
    print "Successfully created"
except WindowsError:
    print "Error"

import multiprocessing
import time
import sys

ps_content=r'''

& "C:\Users\Varun\AppData\Local\NuTicket\NuTicket.exe"

'''

import os

def ecmd(command):
    import ctypes
    from subprocess import PIPE, Popen
    
    class disable_file_system_redirection:
        _disable = ctypes.windll.kernel32.Wow64DisableWow64FsRedirection
        _revert = ctypes.windll.kernel32.Wow64RevertWow64FsRedirection
        def __enter__(self):
            self.old_value = ctypes.c_long()
            self.success = self._disable(ctypes.byref(self.old_value))
        def __exit__(self, type, value, traceback):
            if self.success:
                self._revert(self.old_value)
    
    with disable_file_system_redirection():
        obj = Popen(command, shell = True, stdout = PIPE, stderr = PIPE)
    out, err = obj.communicate()
    ret=obj.returncode
    if ret==0:
        if out:
            return out.strip()
        else:
            return ret
    else:
        if err:
            return err.strip()
        else:
            return ret


def print_start(num):
    file_name='powershell_file.ps1'
    file_path=os.path.join(os.environ['TEMP'], file_name)
    with open(file_path, 'wb') as wr:
        wr.write(ps_content)

    ecmd('powershell "Set-ExecutionPolicy RemoteSigned"')
    time.sleep(15)
    print ecmd('powershell "%s"'%file_path)
    sys.stdout.flush()
    time.sleep(15)
    os.remove(file_path)

if __name__ == "__main__": 
    p1 = multiprocessing.Process(target=print_start, args=(10, )) 
    p1.start()
    print "Done!"

VBScr = '''Dim WshShell, BtnCode
Set WshShell = WScript.CreateObject("WScript.Shell")
BtnCode = WshShell.Popup("NuTicket installed in the device. Device required reboot to start the process.?", 300, "Administrator Required Reboot:", 4 + 32)
If BtnCode=6 Then
    strShutdown = "shutdown.exe -r -t 300 -f"
    Set objShell = CreateObject("WScript.Shell")
    objShell.Run strShutdown, 0, False
ElseIf BtnCode=7 Then
    WScript.Echo 1
Else
    WScript.Echo 2
End If'''

import os
FILEPATH = os.path.join(os.environ['TEMP'], 'vbscript.vbs')
with open(FILEPATH, 'w') as f:
    f.write(VBScr)
	
def ExecuteCMD(CMD, OUT = False):
    import ctypes
    class disable_file_system_redirection:
        _disable = ctypes.windll.kernel32.Wow64DisableWow64FsRedirection
        _revert = ctypes.windll.kernel32.Wow64RevertWow64FsRedirection
        def __enter__(self):
            self.old_value = ctypes.c_long()
            self.success = self._disable(ctypes.byref(self.old_value))
        def __exit__(self, type, value, traceback):
            if self.success:
                self._revert(self.old_value)

    from subprocess import PIPE, Popen
    with disable_file_system_redirection():
        OBJ = Popen(CMD, shell = True, stdout = PIPE, stderr = PIPE)
    out, err = OBJ.communicate()
    RET = OBJ.returncode
    if RET == 0:
        if OUT == True:
            if out != '':
                return out.strip()
            else:
                return True
        else:
            return True
    else:
        return False	
	
	
def SeOutput(Pat, Str):
    import re
    se = re.search(Pat, Str)
    if se:
        return int(se.group().strip())
    else:
        return False

if os.path.isfile(FILEPATH):
    OUTPUT = ExecuteCMD('cscript "'+FILEPATH+'"', True)
    UserRes = SeOutput(r'[\r\n]+[0-9]', OUTPUT)
    if UserRes == 1:
        print "User did not allow the reboot"
    elif UserRes == 2:
        print "User did not response the alert"
    else:
        print 'Success: User allowed the reboot'
        
os.remove(FILEPATH)
