import os
import subprocess
import ctypes
import ssl
import urllib
import time 

url = "https://script-downloads.comodo.com/WM_SDClient/WM_SDClientSetup.msi"
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():
	def uninstall(command):
		cmd = subprocess.Popen(command,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
		result,error=cmd.communicate()
		if error:
			print(error)
		else:
			print('SmartDeploy Client Uninstalled.')
	
	def download(Url):
		try:
			if os.path.exists("C:\\WM-Network-Workstation"):
				pass 
			else:
				os.makedirs("C:\\WM-Network-Workstation")
			print('WM_SDClientSetup File Downloading')
			destination = "C:\\WM-Network-Workstation\\WM_SDClientSetup.msi"
			gcontext = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
			download = urllib.urlretrieve(Url,destination,context = gcontext)
			print('WM_SDClientSetup File downloaded') 
			return "Sucess"
		except:
			return "Error" 

	def install():
		command = 'msiexec /i '+'"'+'C:\\WM-Network-Workstation\\WM_SDClientSetup.msi'+'"'+' /quiet /qn'
		cmd = subprocess.Popen(command,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
		result,error=cmd.communicate()
		if error:
			print("Installation Failed..")
			print(error)
		else:
			print("WM SmartDeploy Client Installed Successfully.")
			

	cmd = subprocess.Popen("wmic product get name",shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
	result,error=cmd.communicate()
	if error:
		print(error)
	else:
		value = result.splitlines()
	for val in value:
		if val.strip() == "SmartDeploy Client":
			print("Already a version of SmartDeploy Client present in your device.")
			print("Uninstalling SmartDeploy Client....")
			Command = 'wmic product where name='+'"'+'SmartDeploy Client'+'"'+' call uninstall'
			uninstall(Command)
		else:
			pass 
	DOWNLOAD = download(url)
	if DOWNLOAD == "Sucess":
		install()
	else:
		print("Download Failed please try again....")

