$OutputEncoding = [System.Text.Encoding]::UTF8

if (-not ([bool]([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator))) {
    Write-Error "Script must be run as Administrator. Aborting."
    exit 1
}

# Проверка, установлен ли Chocolatey
choco -v > $null 2>&1
if ($?) {
    Write-Output "Chocolatey is already installed."
} else {
    Write-Output "Installing Chocolate..."
    Invoke-Expression ((New-Object System.Net.WebClient).DownloadString('https://community.chocolatey.org/install.ps1'))
}

# Установка FFmpeg через Chocolatey
if (-not (Get-Command ffmpeg -ErrorAction SilentlyContinue)) {
    Write-Output "Installing FFmpeg..."
    choco install ffmpeg -y
} else {
    Write-Output "FFmpeg is already installed."
}

[string]$zipPath = "C:\Builds\Latest.zip"
[string]$targetPath = "C:\inetpub\alcotester"  # Target directory for all IIS files

# Ensure ZIP file exists
if (!(Test-Path $zipPath)) {
    Write-Output "ZIP file not found: $zipPath"
    exit 1
}

# Temporary extraction path
$tempExtractPath = "C:\inetpub_temp"

# Stop IIS to unlock files
Write-Output "Stopping IIS..."
Stop-Service -Name W3SVC -Force

# Remove old files except Scripts folder
Write-Output "Removing old files in C:\inetpub except Scripts..."
Get-ChildItem -Path $targetPath | Where-Object { $_.Name -ne "Scripts" } | Remove-Item -Recurse -Force -ErrorAction SilentlyContinue

# Extract ZIP
Write-Output "Extracting ZIP..."
Expand-Archive -Path $zipPath -DestinationPath $tempExtractPath -Force

# Copy new files to inetpub
Write-Output "Updating files..."
Copy-Item -Path "$tempExtractPath\combined\publish\*" -Destination $targetPath -Recurse -Force

# Clean up temp files
Write-Output "Cleaning up..."
Remove-Item -Path $tempExtractPath -Recurse -Force -ErrorAction SilentlyContinue

# Start IIS
Write-Output "Starting IIS..."
Start-Service -Name W3SVC
 
Write-Output "Update complete!"

