#Requires -RunAsAdministrator
<#
.SYNOPSIS
  Install the iVistaar admin site on IIS from an unzipped release folder.
  No Git is required.

.PARAMETER SiteName
  IIS site name (default: iVistaar)

.PARAMETER AppPoolName
  App pool for the admin UI (default: IVistaar_Admin)

.PARAMETER PhysicalPath
  Path to the unzipped iVistaar folder (contains wsgi.py / admin/).
  Defaults to the parent of the scripts\ folder (so you can run this from C:\iVistaar).

.PARAMETER Port
  HTTP port binding (default: 80)

.PARAMETER HostHeader
  Optional host header, e.g. ivistaar.company.com

.PARAMETER PythonPath
  Full path to python.exe used for the admin venv
#>
param(
    [string]$SiteName = "iVistaar",
    [string]$AppPoolName = "IVistaar_Admin",
    [string]$PhysicalPath = "",
    [int]$Port = 80,
    [string]$HostHeader = "",
    [string]$PythonPath = "python"
)

$ErrorActionPreference = "Stop"
Import-Module WebAdministration

if (-not $PhysicalPath) {
    # scripts\install-admin.ps1 → parent is the iVistaar root
    $PhysicalPath = Split-Path -Parent $PSScriptRoot
}

if (-not (Test-Path (Join-Path $PhysicalPath "wsgi.py"))) {
    throw "wsgi.py not found in '$PhysicalPath'. Extract the iVistaar zip and run this script from that folder."
}

$PhysicalPath = (Resolve-Path $PhysicalPath).Path
Write-Host "Installing iVistaar admin from $PhysicalPath (no Git required)"

# Ensure HttpPlatformHandler is present
$hpp = Get-WebGlobalModule | Where-Object { $_.Name -eq "httpPlatformHandler" }
if (-not $hpp) {
    Write-Warning "httpPlatformHandler module not found. Install HttpPlatformHandler from https://www.iis.net/downloads/microsoft/httpplatformhandler"
}

# Create admin venv + deps
$venvPython = Join-Path $PhysicalPath "venv\Scripts\python.exe"
if (-not (Test-Path $venvPython)) {
    Write-Host "Creating admin venv..."
    & $PythonPath -m venv (Join-Path $PhysicalPath "venv")
    if ($LASTEXITCODE -ne 0) { throw "Failed to create venv" }
}
Write-Host "Installing admin requirements..."
& $venvPython -m pip install --upgrade pip
& $venvPython -m pip install -r (Join-Path $PhysicalPath "requirements.txt")
if ($LASTEXITCODE -ne 0) { throw "pip install failed" }

# data + logs + apps root
New-Item -ItemType Directory -Force -Path (Join-Path $PhysicalPath "data\logs") | Out-Null
New-Item -ItemType Directory -Force -Path (Join-Path $PhysicalPath "data\uploads") | Out-Null
New-Item -ItemType Directory -Force -Path (Join-Path $PhysicalPath "logs") | Out-Null
$appsRoot = "D:\iVistaar\apps"
New-Item -ItemType Directory -Force -Path $appsRoot | Out-Null

# Admin web.config
$webConfig = @"
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <system.webServer>
    <handlers>
      <add name="httpPlatformHandler" path="*" verb="*" modules="httpPlatformHandler" resourceType="Unspecified" requireAccess="Script" />
    </handlers>
    <httpPlatform processPath=".\venv\Scripts\python.exe"
                  arguments="-m waitress --listen=127.0.0.1:%HTTP_PLATFORM_PORT% wsgi:app"
                  stdoutLogEnabled="true"
                  stdoutLogFile=".\logs\stdout_admin.log"
                  startupTimeLimit="120"
                  processesPerApplication="1">
      <environmentVariables>
        <environmentVariable name="PYTHONPATH" value="." />
        <environmentVariable name="IVISTAAR_APPS_ROOT" value="$appsRoot" />
        <environmentVariable name="IVISTAAR_DATA_ROOT" value="$(Join-Path $PhysicalPath 'data')" />
        <environmentVariable name="IVISTAAR_IIS_SITE_NAME" value="$SiteName" />
        <environmentVariable name="IVISTAAR_PUBLIC_BASE_URL" value="http://$(if ($HostHeader) { $HostHeader } else { "localhost:$Port" })" />
        <environmentVariable name="IVISTAAR_DRY_RUN" value="0" />
      </environmentVariables>
    </httpPlatform>
  </system.webServer>
</configuration>
"@
Set-Content -Path (Join-Path $PhysicalPath "web.config") -Value $webConfig -Encoding UTF8

# App pool
if (-not (Test-Path "IIS:\AppPools\$AppPoolName")) {
    New-WebAppPool -Name $AppPoolName | Out-Null
}
Set-ItemProperty "IIS:\AppPools\$AppPoolName" -Name managedRuntimeVersion -Value ""
Set-ItemProperty "IIS:\AppPools\$AppPoolName" -Name startMode -Value "AlwaysRunning"

# Site
$binding = if ($HostHeader) { "*:${Port}:${HostHeader}" } else { "*:${Port}:" }
if (-not (Get-Website -Name $SiteName -ErrorAction SilentlyContinue)) {
    New-Website -Name $SiteName -PhysicalPath $PhysicalPath -ApplicationPool $AppPoolName -Port $Port -HostHeader $HostHeader | Out-Null
} else {
    Set-ItemProperty "IIS:\Sites\$SiteName" -Name physicalPath -Value $PhysicalPath
    Set-ItemProperty "IIS:\Sites\$SiteName" -Name applicationPool -Value $AppPoolName
}

# Ensure /apps virtual directory root exists as a folder mapping placeholder
$appsPhysical = $appsRoot
if (-not (Test-Path "IIS:\Sites\$SiteName\apps")) {
    # Create an empty marker folder and a path segment container application is optional;
    # each deploy creates /apps/<slug> applications via provision-app.ps1
    New-Item -ItemType Directory -Force -Path (Join-Path $appsPhysical "_placeholder") | Out-Null
}

Restart-WebAppPool -Name $AppPoolName
Write-Host ""
Write-Host "iVistaar admin installed."
Write-Host "  Site:    $SiteName"
Write-Host "  Pool:    $AppPoolName"
Write-Host "  Binding: $binding"
Write-Host "  Login:   admin / iV!5taar#Ctrl2026"
Write-Host "Open http://$(if ($HostHeader) { $HostHeader } elseif ($Port -eq 80) { 'localhost' } else { "localhost:$Port" })/"
