#Requires -RunAsAdministrator

$installDir      = "C:\DeployPro"
$nodeDir         = "C:\Program Files\nodejs"
$appPoolIdentity = "IIS AppPool\DeployPro"

Write-Host "Fixing permissions for: $appPoolIdentity"
Write-Host ""

# 1. Grant Modify on the app install directory (recursive)
Write-Host "[1] App directory: $installDir"
& icacls $installDir /grant "${appPoolIdentity}:(OI)(CI)M" /T /Q
Write-Host "    Done."

# 2. Grant Read+Execute on Node.js directory so the pool can run node.exe
Write-Host "[2] Node.js directory: $nodeDir"
& icacls $nodeDir /grant "${appPoolIdentity}:(OI)(CI)RX" /T /Q
Write-Host "    Done."

# 3. Grant Read+Execute on node.exe specifically (belt-and-suspenders)
$nodeExe = Join-Path $nodeDir "node.exe"
if (Test-Path $nodeExe) {
    Write-Host "[3] node.exe: $nodeExe"
    & icacls $nodeExe /grant "${appPoolIdentity}:RX" /Q
    Write-Host "    Done."
}

# 4. Recycle the app pool
Write-Host "[4] Recycling app pool..."
Import-Module WebAdministration -ErrorAction SilentlyContinue
if (Get-WebConfiguration "system.applicationHost/applicationPools/add[@name='DeployPro']") {
    Restart-WebAppPool "DeployPro"
    Write-Host "    Pool recycled."
} else {
    Write-Host "    Pool 'DeployPro' not found - recycle manually."
}

Write-Host ""
Write-Host "All done. Try refreshing the browser now."
