import os
import ssl
import ctypes
import urllib2
from subprocess import PIPE, Popen

server_address = itsm.getParameter('ServerURL') ##Provide your Server URL

# Path where the OCS Inventory Agent typically gets installed
INSTALLATION_PATH = r"C:\Program Files\OCS Inventory Agent\OcsSystray.exe"

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)

# Determine architecture
with disable_file_system_redirection():
    arch = os.popen("wmic os get OSArchitecture").read()

if '64' in arch:
    url = "https://cdn-patchportal-one.comodo.com/portal/packages/spm/OCS%20Inventory%20NG%20Agent/x64/OCS-Windows-Agent-Setup-x64.exe"
else:
    url = "https://cdn-patchportal-one.comodo.com/portal/packages/spm/OCS%20Inventory%20NG%20Agent/x86/OCS-Windows-Agent-Setup-x86.exe"

Down_path = os.environ['TEMP']
fileName = url.split('/')[-1]
DownTo = os.path.join(Down_path, fileName)

def ecmd(command):   
    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 downloadFile(DownTo, fromURL):
    headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36'}
    context = ssl._create_unverified_context()
    try:
        request = urllib2.Request(fromURL, headers=headers)
        req = urllib2.urlopen(request, context=context)
        with open(DownTo, 'wb') as f:
            while True:
                chunk = req.read(1024 * 1024)  # 1MB chunks
                if chunk:
                    f.write(chunk)
                else:
                    break
        if os.path.isfile(DownTo):
            return '{} - {}KB'.format(DownTo, os.path.getsize(DownTo) / 1024)
    except urllib2.URLError as e:
        return 'URL Error: {}'.format(str(e))
    except IOError as e:
        return 'IO Error: {}'.format(str(e))
    except Exception as e:
        return 'Error: {}'.format(str(e))

def is_already_installed():
    """Check if OCS Inventory Agent is already installed."""
    if os.path.isfile(INSTALLATION_PATH):
        print("OCS Inventory Agent is already installed.")
        return True
    else:
        return False

def install():
    if not is_already_installed():
        with disable_file_system_redirection():
            print("OCS Inventory Agent not found. Starting download and installation...")
            download_result = downloadFile(DownTo, url)
            print(download_result)
            if 'Error' not in download_result:
                print(ecmd('"%s" /S /SERVER="%s"' % (DownTo, server_address)))
                if os.path.isfile(DownTo):
                    os.remove(DownTo)
            else:
                print("Download failed. Installation aborted.")
    else:
        print("Skipping installation as OCS Inventory Agent is already installed.")

if __name__ == "__main__":
    install()
