URL = 'https://www.iconarchive.com/download/i38830/google/chrome/Google-Chrome.ico'  # Icon download URL
src_path = r"C:\ProgramData\website_icons"  # Folder to save the downloaded icon
Display_icon_name = "Google"  # Name shown below the desktop icon
fileName = 'google.ico'  # Icon file name
Website_To_Open_When_Clicked_On_Icon = "www.google.com"  # Website opened by the shortcut
Browser_To_Open_Given_Website = "Edge"  # Edge or Chrome
Open_the_website_everytime_user_logins = "yes"  # yes or no

import os
import sys
import ctypes
import urllib2
import ssl
import shutil
import datetime
import _winreg as winreg

LOG_FILE = "C:\\Windows\\Temp\\website_shortcut.log"


def log(level, msg):
    ts = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    line = ts + " [" + level + "] " + str(msg)
    print line
    sys.stdout.flush()
    try:
        f = open(LOG_FILE, "a")
        f.write(line + "\n")
        f.close()
    except Exception:
        pass


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 check_and_change(icopath, src_path):
    if os.path.exists(icopath):
        log("INFO", "Icon file already exists, changing filename to prevent overwriting")
        dt = datetime.datetime.now()
        name = fileName.split('.')
        new_name = name[0] + "_" + dt.strftime("%d%m%Y_%H%M%S") + "." + name[-1]
        return os.path.join(src_path, new_name)
    return icopath


def download_icon(src_path, url):
    log("INFO", "Icon download started")
    icopath = os.path.join(src_path, fileName)
    if not os.path.exists(src_path):
        os.makedirs(src_path)
        log("INFO", "Icon folder created: " + src_path)
    fp = check_and_change(icopath, src_path)
    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'}
    request = urllib2.Request(url, headers=headers)
    context = ssl._create_unverified_context()
    parsed = urllib2.urlopen(request, context=context)
    with open(fp, 'wb') as f:
        while True:
            chunk = parsed.read(1024 * 1024)
            if not chunk:
                break
            f.write(chunk)
    log("INFO", "Icon downloaded to: " + fp)
    return fp


def find_browser(name):

    rel = {
        "chrome": r"Google\Chrome\Application\chrome.exe",
        "edge": r"Microsoft\Edge\Application\msedge.exe",
    }.get(name)
    if rel is None:
        log("ERROR", "Unsupported browser value: " + name)
        return None


    bases = [r"C:\Program Files", r"C:\Program Files (x86)"]
    for var in ("ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"):
        v = os.environ.get(var)
        if v and v not in bases:
            bases.append(v)
    for b in bases:
        p = os.path.join(b, rel)
        if os.path.exists(p):
            log("INFO", "Found browser at: " + p)
            return p


    exe = os.path.basename(rel)
    key_path = r"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\%s" % exe
    for hive in (winreg.HKEY_LOCAL_MACHINE, winreg.HKEY_CURRENT_USER):
        try:
            k = winreg.OpenKey(hive, key_path, 0, winreg.KEY_READ | winreg.KEY_WOW64_64KEY)
            p = winreg.QueryValueEx(k, "")[0]
            winreg.CloseKey(k)
            if p and os.path.exists(p):
                log("INFO", "Found browser via App Paths: " + p)
                return p
        except WindowsError:
            pass
    return None


def runvbs(vbs):
    workdir = os.environ['PROGRAMDATA'] + r'\temp'
    if not os.path.isdir(workdir):
        os.mkdir(workdir)
    vbs_file = workdir + r'\temprun.vbs'
    with open(vbs_file, "w") as f:
        f.write(vbs)
    with disable_file_system_redirection():
        out = os.popen('cscript.exe //nologo "' + vbs_file + '"').read()
    if out.strip():
        log("INFO", "cscript output: " + out.strip())
    if os.path.isfile(vbs_file):
        os.remove(vbs_file)


def main():
    log("INFO", "Script started. Browser=" + Browser_To_Open_Given_Website + " Site=" + Website_To_Open_When_Clicked_On_Icon)

    browser_exe = find_browser(Browser_To_Open_Given_Website.lower())
    if not browser_exe:
        log("ERROR", Browser_To_Open_Given_Website + " not found on this endpoint. Shortcut not created.")
        sys.exit(2)
    browser_path = '"' + browser_exe + '"'

    icon_file = download_icon(src_path, URL)
    icon_path = '"' + icon_file + '"'

    vbs = '''
Set WshShell = WScript.CreateObject("WScript.Shell")
strDesktop = WshShell.SpecialFolders("AllUsersDesktop")
Set oShellLink = WshShell.CreateShortcut(strDesktop & "\\%s.lnk")
oShellLink.TargetPath = %s
oShellLink.WindowStyle = 1
oShellLink.IconLocation = %s
oShellLink.Hotkey = "CTRL+SHIFT+F"
oShellLink.Description = "Shortcut Script"
oShellLink.WorkingDirectory = strDesktop
oShellLink.Arguments = "%s"
oShellLink.Save
''' % (Display_icon_name, browser_path, icon_path, Website_To_Open_When_Clicked_On_Icon)

    runvbs(vbs)

    shortcut = r"C:\Users\Public\Desktop\%s.lnk" % Display_icon_name
    if not os.path.exists(shortcut):
        log("ERROR", "Shortcut was not created: " + shortcut)
        sys.exit(2)
    log("INFO", "Shortcut created: " + shortcut + " -> " + browser_path)

    if Open_the_website_everytime_user_logins.lower() == "yes":
        startup = r"C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp"
        shutil.copy2(shortcut, startup)
        log("INFO", "Shortcut copied to Startup folder")

    log("INFO", "Completed successfully")
    return


if __name__ == "__main__":
    try:
        main()
    except SystemExit:
        raise
    except Exception as e:
        log("CRITICAL", "Unhandled exception: " + str(e))
        sys.exit(3)