#Requires -RunAsAdministrator
<#
.SYNOPSIS
  Remove an IIS application and its app pool created by iVistaar.
#>
param(
    [Parameter(Mandatory = $true)][string]$SiteName,
    [Parameter(Mandatory = $true)][string]$AppPoolName,
    [Parameter(Mandatory = $true)][string]$AppPath
)

$ErrorActionPreference = "Stop"
Import-Module WebAdministration

if (-not $AppPath.StartsWith("/")) { $AppPath = "/$AppPath" }
$appName = $AppPath.TrimStart("/")

Write-Host "Removing IIS application $appName and pool $AppPoolName"

$existing = Get-WebApplication -Site $SiteName -Name $appName -ErrorAction SilentlyContinue
if ($existing) {
    Remove-WebApplication -Site $SiteName -Name $appName
}

if (Test-Path "IIS:\AppPools\$AppPoolName") {
    if ((Get-WebAppPoolState -Name $AppPoolName).Value -ne "Stopped") {
        Stop-WebAppPool -Name $AppPoolName
        Start-Sleep -Seconds 1
    }
    Remove-WebAppPool -Name $AppPoolName
}

Write-Host "Removed $appName"
