"""
qBittorrent Updater for Windows (x64)
by Paper

This could be easily ported to macOS/Linux, but for the former it
would just be easier to do it in AppleScript, and for the latter
you should already be using a package manager to do this for you.
"""
import urllib.request
import re
import psutil
import os
import platform
import time


def _check_running(exename):
    for proc in psutil.process_iter():
        try:
            if proc.name() == exename:
                return True
        except psutil.NoSuchProcess as err:
            return False
        except psutil.AccessDenied:
            return False


QBITTORRENT_DIRECTORY = "C:\\Program Files\\qBittorrent"
TEMP_DIRECTORY = os.getenv("TEMP")
BIT_STR = "_x64" if platform.machine().endswith('64') else ""

if _check_running("qbittorrent.exe"):
    print("qBittorrent is currently running! Please exit it and try again.")
    quit(1)

# Get the link for the latest version, courtesy of SourceForge
urllib.request.urlretrieve(re.search("\<a href=\"(https:\/\/sourceforge\.net\/projects\/qbittorrent\/files\/qbittorrent-win32\/qbittorrent-[0-9\.]+\/qbittorrent_[0-9\.]+" + BIT_STR + "_setup\.exe\/download)\"\>", urllib.request.urlopen("https://www.qbittorrent.org/download.php").read().decode("utf-8")).group(1), os.path.join(TEMP_DIRECTORY, "qbittorrent_setup.exe"))

# Run the installer and wait for it to finish
os.system(os.path.join(TEMP_DIRECTORY, "qbittorrent_setup.exe") + " /S")
while _check_running("qbittorrent_setup.exe"):
    time.sleep(5)

# Cleanup
os.remove(os.path.join(TEMP_DIRECTORY, "qbittorrent_setup.exe"))
