; RemoteLink Agent NSIS Installer
; Requires: NSIS 3.x, the dist/ folder from PyInstaller build
;
; Build:        makensis installer.nsi
;
; Silent install (open enrollment — no token):
;   RemoteLink-Setup.exe /S /SERVER=https://myserver.com
;
; Silent install with enrollment token:
;   RemoteLink-Setup.exe /S /SERVER=https://myserver.com /ENROLL=mytoken
;
; Interactive install:
;   RemoteLink-Setup.exe

!define APP_NAME "RemoteLink Agent"
!define APP_VERSION "1.0.0"
!define APP_PUBLISHER "RemoteLink"
!define INSTALL_DIR "$PROGRAMFILES64\RemoteLink"
!define SERVICE_EXE "remotelink-agent-service.exe"
!define AGENT_EXE "remotelink-agent.exe"
!define REG_KEY "Software\RemoteLink\Agent"
!define UNINSTALL_KEY "Software\Microsoft\Windows\CurrentVersion\Uninstall\RemoteLinkAgent"

Name "${APP_NAME} ${APP_VERSION}"
OutFile "RemoteLink-Setup.exe"
InstallDir "${INSTALL_DIR}"
InstallDirRegKey HKLM "${REG_KEY}" "InstallDir"
RequestExecutionLevel admin
SetCompressor /SOLID lzma

Var ServerURL
Var EnrollToken

!include "MUI2.nsh"
!include "LogicLib.nsh"

!define MUI_ABORTWARNING
!define MUI_ICON "assets\icon.ico"
!define MUI_UNICON "assets\icon.ico"

; Pages shown in interactive mode
!insertmacro MUI_PAGE_WELCOME

; Custom server URL page (interactive only)
Page custom ServerURLPage ServerURLPageLeave

!insertmacro MUI_PAGE_DIRECTORY
!insertmacro MUI_PAGE_INSTFILES
!insertmacro MUI_PAGE_FINISH

!insertmacro MUI_UNPAGE_CONFIRM
!insertmacro MUI_UNPAGE_INSTFILES

!insertmacro MUI_LANGUAGE "English"

; ── Custom server URL page ────────────────────────────────────────────────────

Var hServerEdit
Var hTokenEdit

Function ServerURLPage
    IfSilent skip_page  ; skip in silent/mass-deploy mode
    nsDialogs::Create 1018
    Pop $0

    ${NSD_CreateLabel} 0 0 100% 20u "Server URL (e.g. https://remotelink.example.com):"
    ${NSD_CreateText} 0 22u 100% 14u "$ServerURL"
    Pop $hServerEdit

    ${NSD_CreateLabel} 0 44u 100% 20u "Enrollment Token (leave blank if open enrollment is enabled):"
    ${NSD_CreateText} 0 66u 100% 14u "$EnrollToken"
    Pop $hTokenEdit

    nsDialogs::Show
    skip_page:
FunctionEnd

Function ServerURLPageLeave
    IfSilent skip
    ${NSD_GetText} $hServerEdit $ServerURL
    ${NSD_GetText} $hTokenEdit $EnrollToken
    ${If} $ServerURL == ""
        MessageBox MB_OK|MB_ICONEXCLAMATION "Server URL is required."
        Abort
    ${EndIf}
    skip:
FunctionEnd

; ── Init: parse command-line ──────────────────────────────────────────────────

Function .onInit
    ${GetParameters} $R0
    ClearErrors
    ${GetOptions} $R0 "/SERVER=" $ServerURL
    ClearErrors
    ${GetOptions} $R0 "/ENROLL=" $EnrollToken

    IfSilent 0 +2
    SetSilent silent
FunctionEnd

; ── Main install section ──────────────────────────────────────────────────────

Section "Install" SEC_MAIN
    SetOutPath "${INSTALL_DIR}"

    ; Stop and remove existing service
    nsExec::ExecToLog '"${INSTALL_DIR}\${SERVICE_EXE}" stop'
    nsExec::ExecToLog '"${INSTALL_DIR}\${SERVICE_EXE}" remove'
    Sleep 1000

    ; Copy binaries
    File "dist\remotelink-agent.exe"
    File "dist\remotelink-agent-service.exe"

    ; Registry
    WriteRegStr HKLM "${REG_KEY}" "InstallDir" "${INSTALL_DIR}"
    WriteRegStr HKLM "${REG_KEY}" "Version" "${APP_VERSION}"
    ${If} $ServerURL != ""
        WriteRegStr HKLM "${REG_KEY}" "ServerURL" "$ServerURL"
    ${EndIf}

    ; Enroll with server
    ${If} $ServerURL != ""
        ${If} $EnrollToken != ""
            DetailPrint "Enrolling with token…"
            nsExec::ExecToLog '"${INSTALL_DIR}\${AGENT_EXE}" --server "$ServerURL" --enroll "$EnrollToken"'
        ${Else}
            DetailPrint "Registering (open enrollment)…"
            nsExec::ExecToLog '"${INSTALL_DIR}\${AGENT_EXE}" --server "$ServerURL"'
        ${EndIf}
    ${EndIf}

    ; Install and start service
    DetailPrint "Installing Windows service…"
    nsExec::ExecToLog '"${INSTALL_DIR}\${SERVICE_EXE}" install'
    nsExec::ExecToLog '"${INSTALL_DIR}\${SERVICE_EXE}" start'

    ; Uninstaller
    WriteUninstaller "${INSTALL_DIR}\Uninstall.exe"
    WriteRegStr HKLM "${UNINSTALL_KEY}" "DisplayName" "${APP_NAME}"
    WriteRegStr HKLM "${UNINSTALL_KEY}" "UninstallString" "${INSTALL_DIR}\Uninstall.exe"
    WriteRegStr HKLM "${UNINSTALL_KEY}" "DisplayVersion" "${APP_VERSION}"
    WriteRegStr HKLM "${UNINSTALL_KEY}" "Publisher" "${APP_PUBLISHER}"
    WriteRegDWORD HKLM "${UNINSTALL_KEY}" "NoModify" 1
    WriteRegDWORD HKLM "${UNINSTALL_KEY}" "NoRepair" 1
SectionEnd

; ── Uninstall section ─────────────────────────────────────────────────────────

Section "Uninstall"
    nsExec::ExecToLog '"${INSTALL_DIR}\${SERVICE_EXE}" stop'
    nsExec::ExecToLog '"${INSTALL_DIR}\${SERVICE_EXE}" remove'
    Sleep 1000

    Delete "${INSTALL_DIR}\remotelink-agent.exe"
    Delete "${INSTALL_DIR}\remotelink-agent-service.exe"
    Delete "${INSTALL_DIR}\agent.json"
    Delete "${INSTALL_DIR}\Uninstall.exe"
    RMDir "${INSTALL_DIR}"

    ; Delete config
    RMDir /r "$APPDATA\RemoteLink"

    DeleteRegKey HKLM "${REG_KEY}"
    DeleteRegKey HKLM "${UNINSTALL_KEY}"
SectionEnd
