#Requires -RunAsAdministrator
# Fix nodeProcessCommandLine in the installed web.config

$installDir     = "C:\DeployPro"
$webConfigPath  = Join-Path $installDir "web.config"

if (-not (Test-Path $webConfigPath)) {
    # Try to find it via IIS
    Import-Module WebAdministration -ErrorAction SilentlyContinue
    $site = Get-Website | Where-Object { $_.Name -like "*Deploy*" } | Select-Object -First 1
    if ($site) {
        $installDir    = $site.PhysicalPath
        $webConfigPath = Join-Path $installDir "web.config"
        Write-Host "Found site at: $installDir"
    }
}

if (-not (Test-Path $webConfigPath)) {
    Write-Host "ERROR: web.config not found at $webConfigPath"
    exit 1
}

# Get full node.exe path
$nodePath = (Get-Command node -ErrorAction SilentlyContinue).Source
if (-not $nodePath) {
    # Try common locations
    foreach ($p in @("C:\Program Files\nodejs\node.exe","C:\Program Files (x86)\nodejs\node.exe")) {
        if (Test-Path $p) { $nodePath = $p; break }
    }
}
if (-not $nodePath) {
    Write-Host "ERROR: node.exe not found"
    exit 1
}

# Use 8.3 short path to avoid spaces-in-path issue with some iisnode versions
$shortPath = $null
try {
    $fso = New-Object -ComObject Scripting.FileSystemObject
    $shortPath = $fso.GetFile($nodePath).ShortPath
} catch {}

$usePath = if ($shortPath) { $shortPath } else { $nodePath }

Write-Host "node.exe full path  : $nodePath"
Write-Host "node.exe short path : $usePath"
Write-Host "Patching            : $webConfigPath"

$content = Get-Content $webConfigPath -Raw
$patched  = $content -replace 'nodeProcessCommandLine="[^"]*"', "nodeProcessCommandLine=`"$usePath`""
[System.IO.File]::WriteAllText($webConfigPath, $patched, [System.Text.Encoding]::UTF8)

Write-Host "Done. Recycling app pool..."

Import-Module WebAdministration -ErrorAction SilentlyContinue
$site = Get-Website | Where-Object { $_.PhysicalPath -like "*$([System.IO.Path]::GetFileName($installDir))*" -or $_.Name -like "*Deploy*" } | Select-Object -First 1
if ($site) {
    Restart-WebAppPool $site.ApplicationPool
    Write-Host "App pool '$($site.ApplicationPool)' recycled."
} else {
    Write-Host "Could not find site to recycle — recycle the app pool manually in IIS Manager."
}
