param(
    [string]$Label = "snapshot"
)

$ErrorActionPreference = "Stop"

$siteRoot = (Resolve-Path (Join-Path $PSScriptRoot "..")).ProviderPath
$oldRoot = Join-Path $siteRoot ".old"
$safeLabel = ($Label -replace "[^A-Za-z0-9._-]", "-").Trim("-")

if ([string]::IsNullOrWhiteSpace($safeLabel)) {
    $safeLabel = "snapshot"
}

$timestamp = Get-Date -Format "yyyyMMdd-HHmmss"
$snapshot = Join-Path $oldRoot "$timestamp-$safeLabel"

New-Item -ItemType Directory -Force -Path $snapshot | Out-Null

$oldDir = Get-Item -LiteralPath $oldRoot -Force
$oldDir.Attributes = $oldDir.Attributes -bor [System.IO.FileAttributes]::Hidden

$excludeDirs = @(".git", ".old")

Get-ChildItem -LiteralPath $siteRoot -Force | Where-Object {
    $excludeDirs -notcontains $_.Name
} | ForEach-Object {
    Copy-Item -LiteralPath $_.FullName -Destination $snapshot -Recurse -Force
}

icacls (Resolve-Path -LiteralPath $snapshot).ProviderPath /remove:g "*S-1-1-0" /T | Out-Null

Write-Host "Saved snapshot: $snapshot"
