#Requires -RunAsAdministrator
<#
.SYNOPSIS
    Phase 4.5: Archive the SynologyDrive folder on CS-SERVER.
.DESCRIPTION
    Renames the SynologyDrive share folder to indicate it's archived and
    should be deleted after 30 days. Run ONLY after all users are confirmed
    working with mapped drives to CS-SERVER shares.
#>

$SourcePath = "D:\Shares\SynologyDrive"
$ArchiveName = "_SynologyDrive_ARCHIVE_DeleteAfter30Days"
$ArchivePath = "D:\Shares\$ArchiveName"
$DeleteDate = (Get-Date).AddDays(30).ToString("yyyy-MM-dd")

Write-Host "=== Phase 4.5: Archive SynologyDrive ===" -ForegroundColor Cyan
Write-Host ""

if (-not (Test-Path $SourcePath)) {
    Write-Host "[SKIP] $SourcePath does not exist (already archived?)" -ForegroundColor Yellow
    if (Test-Path $ArchivePath) {
        Write-Host "  Archive exists at: $ArchivePath" -ForegroundColor DarkGray
    }
    exit 0
}

# Check if there's an SMB share pointing to SynologyDrive
$share = Get-SmbShare | Where-Object { $_.Path -eq $SourcePath } -ErrorAction SilentlyContinue
if ($share) {
    Write-Host "Removing SMB share: $($share.Name)" -ForegroundColor Yellow
    Remove-SmbShare -Name $share.Name -Force
    Write-Host "  [OK] SMB share removed" -ForegroundColor Green
}

# Get size info
$stats = Get-ChildItem $SourcePath -Recurse -File -ErrorAction SilentlyContinue
$sizeGB = [math]::Round(($stats | Measure-Object Length -Sum).Sum / 1GB, 2)
Write-Host ""
Write-Host "SynologyDrive stats:" -ForegroundColor Cyan
Write-Host "  Files: $($stats.Count)" -ForegroundColor Cyan
Write-Host "  Size:  $sizeGB GB" -ForegroundColor Cyan
Write-Host ""

# Rename
Write-Host "Archiving..." -ForegroundColor Yellow
try {
    Rename-Item $SourcePath $ArchiveName
    Write-Host "[OK] Renamed to: $ArchivePath" -ForegroundColor Green
    Write-Host ""
    Write-Host "IMPORTANT:" -ForegroundColor Yellow
    Write-Host "  Safe to delete after: $DeleteDate" -ForegroundColor Yellow
    Write-Host "  Set a calendar reminder!" -ForegroundColor Yellow

    # Create a readme in the archive
    @"
THIS FOLDER IS ARCHIVED
========================
Archived on: $(Get-Date -Format "yyyy-MM-dd HH:mm")
Safe to delete after: $DeleteDate
Reason: Migrated to CS-SERVER mapped drives (Phase 4 of network migration)

If you need to restore:
  Rename-Item "$ArchivePath" "SynologyDrive"
"@ | Out-File "$ArchivePath\_ARCHIVE_README.txt"

}
catch {
    Write-Host "[ERROR] Failed to archive: $_" -ForegroundColor Red
}

Write-Host "`n=== Archive Complete ===" -ForegroundColor Cyan
