' =============================================================================
' ProTracker Agent — Uninstaller v1.0
' Completely removes the ProTracker agent from this Windows machine.
' Double-click to run. Requests admin elevation if available.
' =============================================================================
Option Explicit

Dim oShell, oFSO, oWshEnv
Set oShell  = CreateObject("WScript.Shell")
Set oFSO    = CreateObject("Scripting.FileSystemObject")
Set oWshEnv = oShell.Environment("PROCESS")

' ── Paths ────────────────────────────────────────────────────────────────────
Dim sAppData, sInstallDir, sStartup
sAppData   = oWshEnv("APPDATA")
sInstallDir = sAppData & "\PrologTracker"     ' User-install path
Dim sInstallDirAdmin
sInstallDirAdmin = "C:\PrologTracker"         ' Admin-install path (old location)
sStartup   = oShell.SpecialFolders("Startup")

Const SERVICE_NAME = "PROLOGTracker"
Const REG_RUN      = "HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Run\PROLOGTracker"

' ── Confirm ──────────────────────────────────────────────────────────────────
Dim ans
ans = MsgBox("This will PERMANENTLY remove the ProTracker Agent from this machine." & vbCrLf & vbCrLf & _
             "All tracking data remains on the ProTracker server." & vbCrLf & _
             "Only the local agent files will be deleted." & vbCrLf & vbCrLf & _
             "Are you sure you want to uninstall?", _
             vbYesNo + vbExclamation, "ProTracker — Uninstall")

If ans <> vbYes Then
    WScript.Quit 0
End If

' ── Elevate if possible (for service removal) ─────────────────────────────────
If Not IsElevated() Then
    Dim r
    r = MsgBox("Running as standard user. Some components may not be fully removed." & vbCrLf & vbCrLf & _
               "Click Yes to retry with admin rights (recommended)." & vbCrLf & _
               "Click No to continue without admin.", _
               vbYesNo + vbQuestion, "ProTracker Uninstall")
    If r = vbYes Then
        ElevateAndRestart
        WScript.Quit 0
    End If
End If

Dim log
log = "ProTracker Uninstall Log" & vbCrLf & Now() & vbCrLf & String(50,"=") & vbCrLf

' ── Step 1: Stop all Python processes running the agent ──────────────────────
log = log & vbCrLf & "[1] Killing agent processes..."
oShell.Run "cmd /c taskkill /f /im pythonw.exe >nul 2>&1", 0, True
oShell.Run "cmd /c taskkill /f /im python.exe  >nul 2>&1", 0, True
WScript.Sleep 1500
log = log & " done" & vbCrLf

' ── Step 2: Remove Windows Service (requires admin) ──────────────────────────
log = log & "[2] Removing Windows Service..."
Dim sNssm
sNssm = sInstallDir & "\nssm.exe"
If Not oFSO.FileExists(sNssm) Then sNssm = sInstallDirAdmin & "\nssm.exe"

If oFSO.FileExists(sNssm) Then
    oShell.Run Chr(34) & sNssm & Chr(34) & " stop " & SERVICE_NAME & " confirm", 0, True
    WScript.Sleep 1000
    oShell.Run Chr(34) & sNssm & Chr(34) & " remove " & SERVICE_NAME & " confirm", 0, True
    log = log & " removed via NSSM" & vbCrLf
Else
    ' Try sc.exe directly
    oShell.Run "cmd /c sc stop "   & SERVICE_NAME & " >nul 2>&1", 0, True
    WScript.Sleep 1000
    oShell.Run "cmd /c sc delete " & SERVICE_NAME & " >nul 2>&1", 0, True
    log = log & " removed via sc.exe" & vbCrLf
End If

' ── Step 3: Remove Task Scheduler tasks ──────────────────────────────────────
log = log & "[3] Removing scheduled tasks..."
oShell.Run "cmd /c schtasks /delete /tn PROLOGTracker /f >nul 2>&1", 0, True
oShell.Run "cmd /c schtasks /delete /tn PROLOGWatchdog /f >nul 2>&1", 0, True
log = log & " done" & vbCrLf

' ── Step 4: Remove Registry Run key ──────────────────────────────────────────
log = log & "[4] Removing registry entries..."
On Error Resume Next
oShell.RegDelete REG_RUN
' Also try HKLM version (admin installs)
oShell.RegDelete "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run\PROLOGTracker"
On Error GoTo 0
log = log & " done" & vbCrLf

' ── Step 5: Remove Startup folder shortcuts ──────────────────────────────────
log = log & "[5] Removing startup shortcuts..."
Dim sAgentLnk, sWdogLnk, sAgentBat
sAgentLnk = sStartup & "\PROLOGTracker.lnk"
sWdogLnk  = sStartup & "\PROLOGWatchdog.lnk"
sAgentBat = sStartup & "\PROLOGTracker.bat"

If oFSO.FileExists(sAgentLnk) Then oFSO.DeleteFile sAgentLnk, True
If oFSO.FileExists(sWdogLnk)  Then oFSO.DeleteFile sWdogLnk,  True
If oFSO.FileExists(sAgentBat) Then oFSO.DeleteFile sAgentBat, True
log = log & " done" & vbCrLf

' ── Step 6: Delete install directories ───────────────────────────────────────
log = log & "[6] Deleting install directories..."
Dim deleted
deleted = False

If oFSO.FolderExists(sInstallDir) Then
    On Error Resume Next
    oFSO.DeleteFolder sInstallDir, True
    If Err.Number = 0 Then deleted = True
    On Error GoTo 0
End If

If oFSO.FolderExists(sInstallDirAdmin) Then
    On Error Resume Next
    oFSO.DeleteFolder sInstallDirAdmin, True
    If Err.Number = 0 Then deleted = True
    On Error GoTo 0
End If

If deleted Then
    log = log & " deleted" & vbCrLf
Else
    log = log & " some files could not be deleted (may need reboot)" & vbCrLf
End If

' ── Step 7: Remove Python packages (optional) ─────────────────────────────────
' We do NOT uninstall Python itself — the user may use it for other things.
' We also do NOT remove pywin32/psutil — harmless to leave.

' ── Done ─────────────────────────────────────────────────────────────────────
log = log & vbCrLf & String(50,"=") & vbCrLf & "Uninstall complete: " & Now()

' Write log to Desktop for reference
Dim sDesktop, sLogPath
sDesktop  = oShell.SpecialFolders("Desktop")
sLogPath  = sDesktop & "\ProTracker_Uninstall_Log.txt"
Dim oFile
Set oFile = oFSO.CreateTextFile(sLogPath, True)
oFile.Write log
oFile.Close

MsgBox "ProTracker Agent has been removed from this machine." & vbCrLf & vbCrLf & _
       "A log has been saved to your Desktop:" & vbCrLf & _
       sLogPath & vbCrLf & vbCrLf & _
       "Your data on the ProTracker server is untouched.", _
       vbInformation, "ProTracker — Uninstalled"

WScript.Quit 0

' =============================================================================
' FUNCTIONS
' =============================================================================

Function IsElevated()
    On Error Resume Next
    Dim oExec
    Set oExec = oShell.Exec("net session")
    IsElevated = (Err.Number = 0)
    On Error GoTo 0
End Function

Sub ElevateAndRestart()
    Dim sScript
    sScript = WScript.ScriptFullName
    oShell.Run "powershell -NoProfile -NonInteractive -Command " & _
               Chr(34) & "Start-Process cscript -ArgumentList '" & _
               sScript & "' -Verb RunAs" & Chr(34), 0, False
End Sub
