# iWifiMonitor - Windows Installation Script
# Run Install.bat to install (auto-elevates to Administrator)

$ErrorActionPreference = "Stop"

# Verify running as admin
$isAdmin = ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
if (-not $isAdmin) {
    Write-Host "ERROR: This script requires Administrator privileges." -ForegroundColor Red
    Write-Host "Please run Install.bat instead." -ForegroundColor Yellow
    exit 1
}

$AppName = "iWiFiMonitor"
$ServiceName = "iWiFiMonitor"
$WebServiceName = "iWiFiMonitorWeb"
$InstallDir = "$env:ProgramFiles\$AppName"
$DataDir = "$env:ProgramData\$AppName"
$ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path

Write-Host ""
Write-Host "=========================================="
Write-Host "   iWifiMonitor - Windows Installer"
Write-Host "=========================================="
Write-Host ""

# Check if already installed
$existingService = Get-Service -Name $ServiceName -ErrorAction SilentlyContinue
if ($existingService) {
    Write-Host "Existing installation detected. Stopping services..." -ForegroundColor Yellow
    Stop-Service -Name $WebServiceName -ErrorAction SilentlyContinue
    Stop-Service -Name $ServiceName -ErrorAction SilentlyContinue
    Start-Sleep -Seconds 2

    # Remove old services
    sc.exe delete $WebServiceName 2>$null
    sc.exe delete $ServiceName 2>$null
    Start-Sleep -Seconds 1
}

# Create directories
Write-Host "Creating directories..."
if (-not (Test-Path $InstallDir)) {
    New-Item -ItemType Directory -Force -Path $InstallDir | Out-Null
}
if (-not (Test-Path $DataDir)) {
    New-Item -ItemType Directory -Force -Path $DataDir | Out-Null
}

# Copy application files
Write-Host "Copying application files..."
$appFiles = @(
    "iWiFiMonitor.Service.exe",
    "iWiFiMonitor.Web.exe",
    "appsettings.json",
    "appsettings.Production.json",
    "web.config"
)

# Copy main executables
foreach ($file in $appFiles) {
    $sourcePath = Join-Path $ScriptDir $file
    if (Test-Path $sourcePath) {
        Copy-Item -Path $sourcePath -Destination $InstallDir -Force
    }
}

# Copy wwwroot folder if exists
$wwwrootSource = Join-Path $ScriptDir "wwwroot"
if (Test-Path $wwwrootSource) {
    Copy-Item -Path $wwwrootSource -Destination $InstallDir -Recurse -Force
}

# Copy any remaining files (DLLs, etc.)
Get-ChildItem -Path $ScriptDir -File | Where-Object {
    $_.Extension -in @(".dll", ".json", ".pdb") -or $_.Name -like "*.deps.json" -or $_.Name -like "*.runtimeconfig.json"
} | ForEach-Object {
    Copy-Item -Path $_.FullName -Destination $InstallDir -Force
}

# Install monitoring service
Write-Host "Installing monitoring service..."
$servicePath = Join-Path $InstallDir "iWiFiMonitor.Service.exe"
sc.exe create $ServiceName binPath= "`"$servicePath`"" start= auto DisplayName= "iWifiMonitor Service" | Out-Null
sc.exe description $ServiceName "Monitors WiFi and ISP connectivity and tracks network devices" | Out-Null

# Install web UI service
Write-Host "Installing web UI service..."
$webPath = Join-Path $InstallDir "iWiFiMonitor.Web.exe"
sc.exe create $WebServiceName binPath= "`"$webPath`"" start= auto DisplayName= "iWifiMonitor Web UI" | Out-Null
sc.exe description $WebServiceName "Web dashboard for iWiFi Monitor" | Out-Null

# Configure firewall
Write-Host "Configuring firewall..."
$firewallRule = Get-NetFirewallRule -DisplayName "iWifiMonitor Web UI" -ErrorAction SilentlyContinue
if (-not $firewallRule) {
    New-NetFirewallRule -DisplayName "iWifiMonitor Web UI" -Direction Inbound -Protocol TCP -LocalPort 5280 -Action Allow | Out-Null
}

# Start services
Write-Host "Starting services..."

# Start monitoring service
try {
    Start-Service -Name $ServiceName -ErrorAction Stop
    Write-Host "  - $ServiceName started successfully" -ForegroundColor Green
} catch {
    Write-Host "  - WARNING: $ServiceName failed to start" -ForegroundColor Yellow
    Write-Host "    Check Event Viewer > Windows Logs > Application for details" -ForegroundColor Yellow
}

# Give the first service a moment to initialize
Start-Sleep -Seconds 2

# Start web service
try {
    Start-Service -Name $WebServiceName -ErrorAction Stop
    Write-Host "  - $WebServiceName started successfully" -ForegroundColor Green
} catch {
    Write-Host "  - WARNING: $WebServiceName failed to start" -ForegroundColor Yellow
    Write-Host "    Check Event Viewer > Windows Logs > Application for details" -ForegroundColor Yellow
    Write-Host ""
    Write-Host "    You can try starting manually:" -ForegroundColor Yellow
    Write-Host "      sc start $WebServiceName" -ForegroundColor Yellow
    Write-Host "    Or run directly to see errors:" -ForegroundColor Yellow
    Write-Host "      `"$InstallDir\iWiFiMonitor.Web.exe`"" -ForegroundColor Yellow
}

# Create Start Menu shortcuts
Write-Host "Creating shortcuts..."
$startMenuDir = "$env:ProgramData\Microsoft\Windows\Start Menu\Programs\$AppName"
if (-not (Test-Path $startMenuDir)) {
    New-Item -ItemType Directory -Force -Path $startMenuDir | Out-Null
}

# Create URL shortcut for dashboard
$shortcutPath = Join-Path $startMenuDir "iWifiMonitor Dashboard.url"
@"
[InternetShortcut]
URL=http://localhost:5280
IconIndex=0
"@ | Out-File -FilePath $shortcutPath -Encoding ASCII

# Create uninstall shortcut
$uninstallShortcut = Join-Path $startMenuDir "Uninstall iWifiMonitor.lnk"
$WshShell = New-Object -ComObject WScript.Shell
$Shortcut = $WshShell.CreateShortcut($uninstallShortcut)
$Shortcut.TargetPath = "powershell.exe"
$Shortcut.Arguments = "-ExecutionPolicy Bypass -File `"$InstallDir\uninstall.ps1`""
$Shortcut.WorkingDirectory = $InstallDir
$Shortcut.Save()

# Copy uninstall script
$uninstallSource = Join-Path $ScriptDir "uninstall.ps1"
if (Test-Path $uninstallSource) {
    Copy-Item -Path $uninstallSource -Destination $InstallDir -Force
}

# Create desktop shortcut (optional)
$desktopShortcut = "$env:PUBLIC\Desktop\iWifiMonitor.url"
@"
[InternetShortcut]
URL=http://localhost:5280
IconIndex=0
"@ | Out-File -FilePath $desktopShortcut -Encoding ASCII

Write-Host ""
Write-Host "=========================================="
Write-Host "   Installation Complete!"
Write-Host "=========================================="
Write-Host ""
Write-Host "Installation directory: $InstallDir"
Write-Host "Data directory: $DataDir"
Write-Host ""
Write-Host "Services installed:"
Write-Host "  - iWiFiMonitor (background monitoring)"
Write-Host "  - iWiFiMonitorWeb (web dashboard)"
Write-Host ""
Write-Host "Dashboard URL: http://localhost:5280"
Write-Host ""

# Open dashboard
$openDashboard = Read-Host "Open dashboard now? (Y/n)"
if ($openDashboard -ne "n" -and $openDashboard -ne "N") {
    Start-Process "http://localhost:5280"
}
