# Sky Art Shop - Deployment Script
# Run this script as Administrator

param(
    [string]$DeployPath = "C:\inetpub\wwwroot\skyartshop",
    [string]$SiteName = "SkyArtShop",
    [switch]$InstallIIS,
    [switch]$CreateSite,
    [switch]$UpdateOnly
)

Write-Host "==================================" -ForegroundColor Cyan
Write-Host "Sky Art Shop Deployment Script" -ForegroundColor Cyan
Write-Host "==================================" -ForegroundColor Cyan
Write-Host ""

# Check if running as Administrator
$isAdmin = ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
if (-not $isAdmin) {
    Write-Host "ERROR: This script must be run as Administrator!" -ForegroundColor Red
    Write-Host "Right-click PowerShell and select 'Run as Administrator'" -ForegroundColor Yellow
    exit 1
}

# Function to install IIS
function Install-IIS {
    Write-Host "Installing IIS features..." -ForegroundColor Yellow
    
    Enable-WindowsOptionalFeature -Online -FeatureName IIS-WebServerRole -NoRestart
    Enable-WindowsOptionalFeature -Online -FeatureName IIS-WebServer -NoRestart
    Enable-WindowsOptionalFeature -Online -FeatureName IIS-CommonHttpFeatures -NoRestart
    Enable-WindowsOptionalFeature -Online -FeatureName IIS-HttpErrors -NoRestart
    Enable-WindowsOptionalFeature -Online -FeatureName IIS-ApplicationDevelopment -NoRestart
    Enable-WindowsOptionalFeature -Online -FeatureName IIS-NetFxExtensibility45 -NoRestart
    Enable-WindowsOptionalFeature -Online -FeatureName IIS-HealthAndDiagnostics -NoRestart
    Enable-WindowsOptionalFeature -Online -FeatureName IIS-HttpLogging -NoRestart
    Enable-WindowsOptionalFeature -Online -FeatureName IIS-Security -NoRestart
    Enable-WindowsOptionalFeature -Online -FeatureName IIS-RequestFiltering -NoRestart
    Enable-WindowsOptionalFeature -Online -FeatureName IIS-Performance -NoRestart
    Enable-WindowsOptionalFeature -Online -FeatureName IIS-WebServerManagementTools -NoRestart
    Enable-WindowsOptionalFeature -Online -FeatureName IIS-ManagementConsole -NoRestart
    Enable-WindowsOptionalFeature -Online -FeatureName IIS-StaticContent -NoRestart
    Enable-WindowsOptionalFeature -Online -FeatureName IIS-DefaultDocument -NoRestart
    Enable-WindowsOptionalFeature -Online -FeatureName IIS-DirectoryBrowsing -NoRestart
    Enable-WindowsOptionalFeature -Online -FeatureName IIS-HttpCompressionStatic -NoRestart
    
    Write-Host "IIS features installed successfully!" -ForegroundColor Green
    Write-Host "NOTE: You may need to restart your computer." -ForegroundColor Yellow
    Write-Host "After restart, install .NET 8.0 Hosting Bundle from:" -ForegroundColor Yellow
    Write-Host "https://dotnet.microsoft.com/download/dotnet/8.0" -ForegroundColor Cyan
}

# Function to publish application
function Publish-Application {
    Write-Host "Publishing application..." -ForegroundColor Yellow
    
    $projectPath = $PSScriptRoot
    
    # Build and publish
    Set-Location $projectPath
    dotnet publish SkyArtShop.csproj -c Release -o $DeployPath
    
    if ($LASTEXITCODE -eq 0) {
        Write-Host "Application published successfully to: $DeployPath" -ForegroundColor Green
    }
    else {
        Write-Host "ERROR: Publishing failed!" -ForegroundColor Red
        exit 1
    }
}

# Function to set permissions
function Set-Permissions {
    Write-Host "Setting folder permissions..." -ForegroundColor Yellow
    
    # Grant IIS permissions
    icacls $DeployPath /grant "IIS_IUSRS:(OI)(CI)F" /T
    icacls $DeployPath /grant "IUSR:(OI)(CI)F" /T
    
    # Ensure uploads folder exists and has permissions
    $uploadsPath = Join-Path $DeployPath "wwwroot\uploads\images"
    if (-not (Test-Path $uploadsPath)) {
        New-Item -Path $uploadsPath -ItemType Directory -Force
    }
    icacls $uploadsPath /grant "IIS_IUSRS:(OI)(CI)F" /T
    
    Write-Host "Permissions set successfully!" -ForegroundColor Green
}

# Function to create IIS site
function Create-IISSite {
    Write-Host "Creating IIS site..." -ForegroundColor Yellow
    
    Import-Module WebAdministration
    
    # Check if site exists
    $existingSite = Get-Website -Name $SiteName -ErrorAction SilentlyContinue
    if ($existingSite) {
        Write-Host "Site '$SiteName' already exists. Updating..." -ForegroundColor Yellow
        Stop-Website -Name $SiteName -ErrorAction SilentlyContinue
        Start-Sleep -Seconds 2
        Remove-Website -Name $SiteName -ErrorAction SilentlyContinue
        Start-Sleep -Seconds 2
    }
    
    # Check if default site is running on port 80
    $defaultSite = Get-Website | Where-Object { $_.Bindings.Collection.bindingInformation -like "*:80:*" -and $_.State -eq "Started" }
    if ($defaultSite -and $defaultSite.Name -ne $SiteName) {
        Write-Host "Stopping '$($defaultSite.Name)' which is using port 80..." -ForegroundColor Yellow
        Stop-Website -Name $defaultSite.Name -ErrorAction SilentlyContinue
    }
    
    # Create new site
    New-Website -Name $SiteName -PhysicalPath $DeployPath -Port 80 -Force
    
    # Configure application pool
    $appPool = Get-Item "IIS:\AppPools\$SiteName" -ErrorAction SilentlyContinue
    if ($appPool) {
        $appPool.managedRuntimeVersion = ""
        $appPool.startMode = "AlwaysRunning"
        $appPool | Set-Item
    }
    
    # Wait a moment before starting
    Start-Sleep -Seconds 2
    
    # Start site
    Start-Website -Name $SiteName -ErrorAction SilentlyContinue
    
    Write-Host "IIS site '$SiteName' created and started!" -ForegroundColor Green
}

# Function to configure firewall
function Configure-Firewall {
    Write-Host "Configuring Windows Firewall..." -ForegroundColor Yellow
    
    # Remove existing rules if they exist
    Remove-NetFirewallRule -DisplayName "SkyArtShop-HTTP" -ErrorAction SilentlyContinue
    
    # Add HTTP rule
    New-NetFirewallRule -DisplayName "SkyArtShop-HTTP" -Direction Inbound -Protocol TCP -LocalPort 80 -Action Allow
    
    Write-Host "Firewall rules configured!" -ForegroundColor Green
}

# Main deployment flow
try {
    if ($InstallIIS) {
        Install-IIS
        exit 0
    }
    
    if ($UpdateOnly) {
        Write-Host "Performing update only..." -ForegroundColor Cyan
        
        # Stop site
        Import-Module WebAdministration
        Stop-Website -Name $SiteName -ErrorAction SilentlyContinue
        Start-Sleep -Seconds 2
        
        # Publish
        Publish-Application
        
        # Start site
        Start-Website -Name $SiteName
        
        Write-Host ""
        Write-Host "Update completed successfully!" -ForegroundColor Green
        exit 0
    }
    
    # Full deployment
    Write-Host "Starting full deployment..." -ForegroundColor Cyan
    Write-Host ""
    
    # Step 1: Publish
    Publish-Application
    
    # Step 2: Set permissions
    Set-Permissions
    
    # Step 3: Create IIS site (if requested)
    if ($CreateSite) {
        Create-IISSite
    }
    
    # Step 4: Configure firewall
    Configure-Firewall
    
    Write-Host ""
    Write-Host "==================================" -ForegroundColor Green
    Write-Host "Deployment completed successfully!" -ForegroundColor Green
    Write-Host "==================================" -ForegroundColor Green
    Write-Host ""
    Write-Host "Next steps:" -ForegroundColor Yellow
    Write-Host "1. Ensure MongoDB is running: net start MongoDB" -ForegroundColor White
    Write-Host "2. Test locally: http://localhost" -ForegroundColor White
    Write-Host "3. Configure your router port forwarding (port 80)" -ForegroundColor White
    Write-Host "4. Update No-IP DUC client" -ForegroundColor White
    Write-Host "5. Test from internet: http://your-noip-hostname.ddns.net" -ForegroundColor White
    Write-Host ""
    Write-Host "Site location: $DeployPath" -ForegroundColor Cyan
    
    if ($CreateSite) {
        Write-Host "IIS Site name: $SiteName" -ForegroundColor Cyan
    }
    
}
catch {
    Write-Host ""
    Write-Host "ERROR: Deployment failed!" -ForegroundColor Red
    Write-Host $_.Exception.Message -ForegroundColor Red
    exit 1
}
