# To define a particular parameter, replace the 'parameterName' inside itsm.getParameter('parameterName') with that parameter's name
import ctypes
import os
import ssl
import subprocess
import urllib2


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 ExecuteCmd(cmd):
    with disable_file_system_redirection():
        obj = subprocess.Popen(["powershell", cmd], shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        out, err = obj.communicate()
        return out, err


def Download(src_path, DURL, APPid):
    filepath = os.path.join(src_path, APPid + '.xpi')
    request = urllib2.Request(DURL, headers={'User-Agent': "Magic Browser"})
    try:
        gcontext = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
        parsed = urllib2.urlopen(request, context=gcontext)
    except:
        parsed = urllib2.urlopen(request)
    if not os.path.exists(src_path):
        os.makedirs(src_path)
    with open(filepath, 'wb') as f:
        while True:
            chunk = parsed.read(100 * 1000 * 1000)
            if chunk:
                f.write(chunk)
            else:
                break
    return filepath


URLS = ['https://addons.mozilla.org/firefox/downloads/file/4047353/ublock_origin-1.46.0.xpi',
        'https://addons.mozilla.org/firefox/downloads/file/4054938/bitwarden_password_manager-2023.1.0.xpi']
appUID = ['uBlock0@raymondhill.net', '{446900e4-71c2-419f-a6a7-df9c091e268b}']
arch = os.popen("wmic os get OSArchitecture").read()
if '64' in arch:
    exePath = r'C:\Program Files\Mozilla Firefox\firefox.exe'
else:
    exePath = r'C:\Program Files (x86)\Mozilla Firefox\firefox.exe'
downloadPath = os.path.dirname(exePath) + r'\distribution\extensions'


if os.path.exists(exePath):
    Res = ''
    for i in range(2):
        filepath = Download(downloadPath, URLS[i], appUID[i])
        if os.path.exists(filepath):
            print "Extension added [" + os.path.basename(URLS[i]) + "]"
        else:
            print "Download failed [" + os.path.basename(URLS[i]) + "]"
else:
    print "Install FireFox before adding extension"
