import os, sys, ctypes, subprocess, time, shutil, urllib.request

SERVER = "116.203.52.248"
KEY = "VoNciHfK04+8tqVDJH8gLs5CbsXpECQ4jBTuFPEt1XU="
RUSTDESK_URL = "https://github.com/rustdesk/rustdesk/releases/download/1.4.5/rustdesk-1.4.5-x86_64.exe"

def is_admin():
    try:
        return ctypes.windll.shell32.IsUserAnAdmin()
    except:
        return False

def run_as_admin():
    ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, f'"{os.path.abspath(sys.argv[0])}"', None, 1)

def msg_box(text, title="CompArt"):
    ctypes.windll.user32.MessageBoxW(0, text, title, 0x40)

if not is_admin():
    run_as_admin()
    sys.exit(0)

msg_box("Clique OK para iniciar a instalacao.", "CompArt Assistencia Remota")

user_profile = os.environ.get("USERPROFILE", "C:\\Users\\user")
appdata = os.path.join(user_profile, "AppData", "Roaming")
localappdata = os.path.join(user_profile, "AppData", "Local")
programfiles = os.environ.get("ProgramFiles", "C:\\Program Files")
programfiles86 = os.environ.get("ProgramFiles(x86)", "C:\\Program Files (x86)")

subprocess.run(["taskkill", "/f", "/im", "rustdesk.exe"], capture_output=True)
subprocess.run(["net", "stop", "RustDesk"], capture_output=True)
subprocess.run(["sc", "stop", "RustDesk"], capture_output=True)
time.sleep(2)

for rd_path in [os.path.join(programfiles, "RustDesk", "rustdesk.exe"),
                 os.path.join(programfiles86, "RustDesk", "rustdesk.exe")]:
    if os.path.exists(rd_path):
        subprocess.run([rd_path, "--uninstall"], capture_output=True, timeout=30)
        time.sleep(3)

subprocess.run(["sc", "delete", "RustDesk"], capture_output=True)
time.sleep(2)

subprocess.run(["reg", "delete", "HKCU\\Software\\RustDesk", "/f"], capture_output=True)
subprocess.run(["reg", "delete", "HKLM\\Software\\RustDesk", "/f"], capture_output=True)

rd_config = os.path.join(appdata, "RustDesk", "config")
if os.path.exists(os.path.dirname(rd_config)):
    shutil.rmtree(os.path.dirname(rd_config), ignore_errors=True)
if os.path.exists(os.path.join(localappdata, "RustDesk")):
    shutil.rmtree(os.path.join(localappdata, "RustDesk"), ignore_errors=True)
os.makedirs(rd_config, exist_ok=True)

dl = os.path.join(os.environ.get("TEMP", "C:\\Temp"), "rustdesk_inst.exe")
urllib.request.urlretrieve(RUSTDESK_URL, dl)

subprocess.Popen([dl, "--silent-install"]).wait()
time.sleep(8)

rd_exe = None
for p in [os.path.join(programfiles, "RustDesk", "rustdesk.exe"),
          os.path.join(programfiles86, "RustDesk", "rustdesk.exe")]:
    if os.path.exists(p):
        rd_exe = p
        break

if not rd_exe:
    msg_box("Erro: instalacao falhou")
    sys.exit(1)

subprocess.run(["taskkill", "/f", "/im", "rustdesk.exe"], capture_output=True)
subprocess.run(["net", "stop", "RustDesk"], capture_output=True)
time.sleep(3)

toml2 = f"""rendezvous_server = '{SERVER}:21116'
nat_type = 1
serial = 0
unlock_pin = ''
trusted_devices = ''

[options]
custom-rendezvous-server = '{SERVER}:21116'
relay-server = '{SERVER}:21117'
key = '{KEY}'
"""
toml1 = f"""key_confirmed = true
"""
toml_path = os.path.join(rd_config, "RustDesk2.toml")
with open(toml_path, "w", encoding="utf-8") as f:
    f.write(toml2)
with open(os.path.join(rd_config, "RustDesk.toml"), "w", encoding="utf-8") as f:
    f.write(toml1)

subprocess.run(["reg", "add", "HKCU\\Software\\RustDesk\\config", "/v", "rendezvous-server", "/t", "REG_SZ", "/d", f"{SERVER}:21116", "/f"], capture_output=True)
subprocess.run(["reg", "add", "HKCU\\Software\\RustDesk\\config", "/v", "relay-server", "/t", "REG_SZ", "/d", f"{SERVER}:21117", "/f"], capture_output=True)
subprocess.run(["reg", "add", "HKCU\\Software\\RustDesk\\config", "/v", "key", "/t", "REG_SZ", "/d", KEY, "/f"], capture_output=True)

subprocess.run([rd_exe, "--import-config", toml_path], capture_output=True, timeout=30)
time.sleep(2)

subprocess.run(["sc", "config", "RustDesk", "start=auto"], capture_output=True)
subprocess.run(["net", "start", "RustDesk"], capture_output=True)
time.sleep(3)
subprocess.run(["taskkill", "/f", "rustdesk.exe"], capture_output=True)
time.sleep(2)
subprocess.Popen([rd_exe])

msg_box(f"Instalacao concluida!\n\nVerifique Settings > Network:\nID Server: {SERVER}\nKey: {KEY}", "CompArt")
