# Install-ProjectRelayServer.ps1
# Run this script in an elevated PowerShell window (Run as administrator).

Write-Host "=== Project-Relay Photo Server Installer (EXE version) ==="
Write-Host ""

# ---- Admin check ----
$principal = New-Object Security.Principal.WindowsPrincipal ([Security.Principal.WindowsIdentity]::GetCurrent())

if (-not $principal.IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)) {
    Write-Host "ERROR: This installer must be run with administrator rights." -ForegroundColor Red
    Write-Host ""
    Write-Host "How to run it correctly:" -ForegroundColor Yellow
    Write-Host "  1) Close this window"
    Write-Host "  2) Open START -> type 'PowerShell'"
    Write-Host "  3) Right-click 'Windows PowerShell' -> Run as administrator"
    Write-Host "  4) Run these commands:"
    Write-Host "       cd `"<path to this folder>`""
    Write-Host "       Set-ExecutionPolicy Bypass -Scope Process -Force"
    Write-Host "       .\\Install-ProjectRelayServer.ps1"
    Write-Host ""
    Write-Host "Press Enter to close this window..."
    [void][System.Console]::ReadLine()
    exit 1
}

# ---- Ask for install folder ----
$defaultInstallPath = "C:\ProjectRelay"
$installPathInput = Read-Host "Install folder (press Enter for default: $defaultInstallPath)"
if ([string]::IsNullOrWhiteSpace($installPathInput)) {
    $installPath = $defaultInstallPath
} else {
    $installPath = $installPathInput
}

Write-Host "Using install folder: $installPath"
Write-Host ""

if (-not (Test-Path -LiteralPath $installPath)) {
    New-Item -ItemType Directory -Path $installPath -Force | Out-Null
}

# ---- Locate ProjectRelay.exe next to this script ----
$scriptDir = Split-Path -Parent $MyInvocation.MyCommand.Definition
$exeSource = Join-Path $scriptDir "ProjectRelayServer.exe"
$exeTarget = Join-Path $installPath "ProjectRelayServer.exe"

if (-not (Test-Path -LiteralPath $exeSource)) {
    Write-Host "ERROR: ProjectRelayServer.exe not found in $scriptDir" -ForegroundColor Red
    Write-Host "Place Install-ProjectRelayServer.ps1 in the same folder as ProjectRelayServer.exe and run again."
    Write-Host "Press Enter to close this window..."
    [void][System.Console]::ReadLine()
    exit 1
}

Write-Host "Copying ProjectRelayServer.exe to $installPath ..."
Copy-Item -Path $exeSource -Destination $exeTarget -Force

# ---- Copy the uninstall script into the install folder (if present) ----
$uninstallSource = Join-Path $scriptDir "Uninstall-ProjectRelayServer.ps1"
if (Test-Path -LiteralPath $uninstallSource) {
    Write-Host "Copying Uninstall-ProjectRelayServer.ps1 to $installPath ..."
    Copy-Item -Path $uninstallSource -Destination (Join-Path $installPath "Uninstall-ProjectRelayServer.ps1") -Force
} else {
    Write-Host "WARNING: Uninstall-ProjectRelayServer.ps1 not found in installer folder." -ForegroundColor Yellow
}

Write-Host ""

# ---- Ask for upload_root (network folder) ----
$defaultUploadRoot = "\\ServerName\ProjectRelay Photos"
$uploadRootInput = Read-Host "Network folder for uploaded photos (press Enter for default: $defaultUploadRoot)"
if ([string]::IsNullOrWhiteSpace($uploadRootInput)) {
    $uploadRoot = $defaultUploadRoot
} else {
    $uploadRoot = $uploadRootInput
}

# ---- Ask for port ----
$defaultPort = 5001
$portInput = Read-Host "Port for the server (press Enter for default: $defaultPort)"

if ([string]::IsNullOrWhiteSpace($portInput)) {
    $port = $defaultPort
} else {
    try {
        $port = [int]$portInput
    } catch {
        Write-Host "Invalid port entered. Using default $defaultPort." -ForegroundColor Yellow
        $port = $defaultPort
    }
}

Write-Host ""
Write-Host "upload_root: $uploadRoot"
Write-Host "port:        $port"
Write-Host ""

# ---- Write config.json ----
$configPath = Join-Path $installPath "config.json"
$configObj = [ordered]@{
    upload_root = $uploadRoot
    port        = $port
}
$configJson = $configObj | ConvertTo-Json -Depth 2
$configJson | Set-Content -Path $configPath -Encoding UTF8

Write-Host "Created config.json in $installPath"
Write-Host ""

# ---- Remove any old Windows service named ProjectRelayServer (if it exists) ----
Write-Host "Cleaning up any old ProjectRelayServer service (if present)..."
sc.exe delete ProjectRelayServer | Out-Null 2>$null

# ---- Create or update Scheduled Task to run the EXE at startup ----
Write-Host "Configuring Scheduled Task 'ProjectRelayServer' to run at startup as SYSTEM..."

# Delete existing task if it exists
schtasks.exe /Delete /TN "ProjectRelayServer" /F | Out-Null 2>$null

# Create new task that runs as SYSTEM on startup
$exeQuoted = '"' + $exeTarget + '"'
schtasks.exe /Create `
    /TN "ProjectRelayServer" `
    /TR $exeQuoted `
    /SC ONSTART `
    /RU "SYSTEM" `
    /F | Out-Null

Write-Host "Scheduled Task 'ProjectRelayServer' created."
Write-Host "The server will start automatically on next boot."

# Optionally start it immediately for this session
Write-Host "Starting ProjectRelayServer.exe now for this session..."
try {
    Start-Process -FilePath $exeTarget
} catch {
    Write-Host "WARNING: Could not start ProjectRelayServer.exe automatically. You can run it manually if needed." -ForegroundColor Yellow
}


# ---- Determine IP for URL ----
$ip = $null

try {
    $candidateIPs = Get-NetIPAddress -AddressFamily IPv4 -ErrorAction SilentlyContinue |
        Where-Object {
            $_.IPAddress -ne "127.0.0.1" -and
            $_.IPAddress -notlike "169.254.*"
        } |
        Select-Object -ExpandProperty IPAddress

    if ($candidateIPs) {
        $private = $candidateIPs | Where-Object {
            $_ -like "192.168.*" -or
            $_ -like "10.*" -or
            ($_ -like "172.*" -and (
                [int]($_.Split('.')[1]) -ge 16 -and
                [int]($_.Split('.')[1]) -le 31
            ))
        }

        if ($private) {
            $ip = $private | Select-Object -First 1
        } else {
            $ip = $candidateIPs | Select-Object -First 1
        }
    }
} catch {
    # ignore
}

if (-not $ip) {
    $ip = "YOUR_SERVER_IP"
}

Write-Host ""
Write-Host ("Upload URL: http://{0}:{1}/upload" -f $ip, $port)
Write-Host ""
Write-Host "Installation complete."
Write-Host "Press Enter to close this window..."
[void][System.Console]::ReadLine()
