[CmdletBinding()]
Param(
    [switch]$AcceptAll
)

$ProgressPreference = 'SilentlyContinue'

function New-TemporaryDirectory {
    $tmp = [System.IO.Path]::GetTempPath()
    $name = (New-Guid).ToString("N")
    New-Item -ItemType Directory -Path (Join-Path $tmp $name)
}

# create a temporary directory and do everything there
Set-Location (New-TemporaryDirectory)

# download the built version of RAWeb and extract to aspx\wwwroot (expected by the respository's install.ps1)
$zipUrl = "https://github.com/kimmknight/raweb/releases/download/v2025.05.22.0/raweb_v2025.05.22.0.zip"
$zipPath = Join-Path $pwd "raweb_v2025.05.22.0.zip"
$extractPath = Join-Path $pwd "aspx\wwwroot"
Write-Host Downloading...
Write-Verbose "Downloading $zipUrl to $zipPath"
Invoke-WebRequest -Uri $zipUrl -OutFile $zipPath
Write-Host Extracting...
Write-Verbose "Extracting $zipPath to $extractPath"
Expand-Archive -Path $zipPath -DestinationPath $extractPath -Force
Write-Verbose "Removing $zipPath"
Remove-Item -Path $zipPath
Write-Host Starting...

# move setup.ps1 to the current directory
$setupPath = Join-Path $extractPath "setup.ps1"
Write-Verbose "Moving $setupPath to $pwd"
Move-Item -Path $setupPath -Destination (Join-Path $pwd "setup.ps1")

# make an empty frontend dir so setup.ps1 does quit due to it
# not being available (it will not be used; the frontend is already built)
$frontendDirPath = Join-Path $pwd "frontend"
Write-Verbose "Creating empty directory $frontendDirPath"
New-Item -ItemType Directory -Force -Path $frontendDirPath | Out-Null

# run setup.ps1
Write-Verbose "Running setup.ps1"
if ($AcceptAll) {
    Write-Verbose "Accepting all prompts"
    Set-ExecutionPolicy Bypass -Scope Process -Force; & ".\setup.ps1" -AcceptAll
} else {
    Set-ExecutionPolicy Bypass -Scope Process -Force; & ".\setup.ps1"
}

# clean up
$loc = $pwd
Write-Verbose "Removing $loc"
Set-Location ~
Remove-Item -Path $loc -Recurse -Force

