# Sync buildable source + Proxmox scripts to the public Gitea repo.
# Allowlist: .publishinclude  |  Skips: Docker, private .gitignore, *.bat, tests, docs, CI, junk
#
# Usage:
#   $env:GITEA_TOKEN = '<token>'
#   .\proxmox\sync-public.ps1 -GiteaUrl https://gitea.example.com -Owner org -Repo myoffice_public -Push

[CmdletBinding()]
param(
	[Parameter(Mandatory = $true)]
	[string]$GiteaUrl,

	[Parameter(Mandatory = $true)]
	[string]$Owner,

	[string]$Repo = 'myoffice-public',

	[string]$Branch = 'master',

	[string]$Token = $env:GITEA_TOKEN,

	[string]$WorkDir = '',

	[switch]$Push
)

$ErrorActionPreference = 'Stop'

$scriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
$repoRoot = Resolve-Path (Join-Path $scriptDir '..')
Set-Location $repoRoot

$GiteaUrl = $GiteaUrl.TrimEnd('/')
$includeFile = Join-Path $repoRoot '.publishinclude'
if (-not (Test-Path $includeFile)) {
	throw "Missing $includeFile"
}

if (-not $WorkDir) {
	$WorkDir = Join-Path $env:TEMP 'myoffice-public-sync'
}

function Test-SkipRel([string]$RelPath) {
	$n = $RelPath -replace '\\', '/'
	$base = Split-Path -Leaf $n

	if ($n -eq 'Docker' -or $n.StartsWith('Docker/')) { return $true }
	if ($base -eq '.gitignore') { return $true }
	if ($base -like '*.bat') { return $true }

	if ($n -eq 'MyOffice.Tests' -or $n.StartsWith('MyOffice.Tests/')) { return $true }
	if ($n -eq 'docs' -or $n.StartsWith('docs/')) { return $true }
	if ($n -eq '.gitea' -or $n.StartsWith('.gitea/')) { return $true }
	if ($base -eq '.dockerignore' -or $base -eq 'gulpfile.js' -or $base -eq 'build.ps1' -or $base -eq 'linux_deploy.sh') { return $true }
	if ($n -eq 'proxmox/README.public.md') { return $true }

	if ($n -match '(^|/)node_modules(/|$)' -or $n -match '(^|/)(bin|obj|\.angular)(/|$)') { return $true }
	if ($n -eq '_Published' -or $n.StartsWith('_Published/') -or $base -eq 'myoffice-publish.tar.gz') { return $true }
	if ($base -eq '.env' -or $base -eq 'env.local' -or $base -like '.env.*') { return $true }
	if ($base -eq 'appsettings.Docker.json' -or $base -eq 'appsettings.shared.Docker.json' -or $base -eq 'environment.docker.ts') { return $true }
	if ($base -like '*.user' -or $base -like '*.suo') { return $true }
	if ($base -eq 'karma.conf.js' -or $base -like '*.spec.ts') { return $true }

	return $false
}

if ($Token) {
	$hostPart = $GiteaUrl -replace '^https://', '' -replace '^http://', ''
	$scheme = if ($GiteaUrl -match '^http://') { 'http' } else { 'https' }
	$remote = "${scheme}://oauth2:${Token}@${hostPart}/${Owner}/${Repo}.git"
}
else {
	$remote = "${GiteaUrl}/${Owner}/${Repo}.git"
	Write-Host "No token — using remote as-is (SSH URL recommended): $remote"
}

Write-Host "-----------------------------------------------"
Write-Host "Sync allowlist (.publishinclude) -> $Owner/$Repo ($Branch)"
Write-Host "WorkDir: $WorkDir"
Write-Host "-----------------------------------------------"

if (Test-Path $WorkDir) {
	Remove-Item -Recurse -Force $WorkDir
}
New-Item -ItemType Directory -Path $WorkDir | Out-Null

$cloned = $false
git clone --depth 1 --branch $Branch $remote $WorkDir 2>$null
if ($LASTEXITCODE -eq 0) { $cloned = $true }

if (-not $cloned) {
	Write-Host "Clone failed or empty repo — initializing new git repo..."
	git -C $WorkDir init -b $Branch
	if ($LASTEXITCODE -ne 0) {
		git -C $WorkDir init
		git -C $WorkDir checkout -b $Branch 2>$null
	}
	git -C $WorkDir remote remove origin 2>$null
	git -C $WorkDir remote add origin $remote
}

Get-ChildItem -Path $WorkDir -Force | Where-Object { $_.Name -ne '.git' } | ForEach-Object {
	Remove-Item $_.FullName -Recurse -Force
}

$tracked = @(git -C $repoRoot ls-files)
$trackedSet = [System.Collections.Generic.HashSet[string]]::new([StringComparer]::OrdinalIgnoreCase)
foreach ($t in $tracked) { [void]$trackedSet.Add(($t -replace '\\', '/')) }

$copied = 0
$skipped = 0

function Copy-Rel([string]$Rel) {
	$script:n = $Rel -replace '\\', '/'
	if (Test-SkipRel $n) {
		$script:skipped++
		return
	}
	$src = Join-Path $repoRoot $n
	if (-not (Test-Path -LiteralPath $src)) { return }
	$dest = Join-Path $WorkDir $n
	$destDir = Split-Path -Parent $dest
	if (-not (Test-Path $destDir)) {
		New-Item -ItemType Directory -Path $destDir -Force | Out-Null
	}
	Copy-Item -LiteralPath $src -Destination $dest -Force
	$script:copied++
}

Get-Content -LiteralPath $includeFile | ForEach-Object {
	$line = $_
	if ($line -match '#') { $line = $line.Substring(0, $line.IndexOf('#')) }
	$line = $line.Trim()
	if (-not $line) { return }

	$norm = $line -replace '\\', '/'
	if ($norm.EndsWith('/')) {
		$prefix = $norm
		$dir = $norm.TrimEnd('/')
		if (-not (Test-Path (Join-Path $repoRoot $dir))) {
			Write-Host "Skip missing dir: $dir"
			return
		}
		foreach ($t in $tracked) {
			$tn = $t -replace '\\', '/'
			if ($tn.StartsWith($prefix)) { Copy-Rel $tn }
		}
		Write-Host "Synced $dir/"
	}
	else {
		if (Test-SkipRel $norm) {
			$skipped++
			Write-Host "Skip excluded: $norm"
			return
		}
		$src = Join-Path $repoRoot $norm
		if (-not (Test-Path -LiteralPath $src)) {
			Write-Host "Skip missing file: $norm"
			return
		}
		Copy-Rel $norm
		Write-Host "Synced $norm"
	}
}

Write-Host "Copied $copied files (skipped $skipped)."

$repoRawBase = "$GiteaUrl/$Owner/$Repo/raw/branch/$Branch"
$template = Join-Path $scriptDir 'README.public.md'
if (-not (Test-Path $template)) { throw "Missing $template" }
$readme = Get-Content -LiteralPath $template -Raw -Encoding utf8
$readme = $readme.
	Replace('__GITEA_URL__', $GiteaUrl).
	Replace('__GITEA_OWNER__', $Owner).
	Replace('__GITEA_REPO__', $Repo).
	Replace('__GITEA_BRANCH__', $Branch).
	Replace('__REPO_RAW_BASE__', $repoRawBase)
Set-Content -LiteralPath (Join-Path $WorkDir 'README.md') -Value $readme -Encoding utf8 -NoNewline
Write-Host "Wrote public README.md"

@(
	'**/bin/',
	'**/obj/',
	'**/node_modules/',
	'**/.angular/',
	'_Published/',
	'myoffice-publish.tar.gz',
	'*.user',
	'.env',
	'env.local',
	'MyOffice.SPA/src/environments/environment.ts',
	'MyOffice.Shared/appsettings.shared.Development.json',
	'MyOffice.Shared/appsettings.shared.Production.json'
) | Set-Content -LiteralPath (Join-Path $WorkDir '.gitignore') -Encoding utf8

git -C $WorkDir add -A
$status = git -C $WorkDir status --porcelain
if (-not $status) {
	Write-Host "No changes to commit."
}
else {
	git -C $WorkDir -c user.email='myoffice-sync@local' -c user.name='myoffice-sync' `
		commit -m "sync build tree from private myoffice"
	Write-Host "Committed public snapshot."
}

if ($Push) {
	Write-Host "Pushing to origin $Branch..."
	git -C $WorkDir push -u origin "HEAD:$Branch"
	if ($LASTEXITCODE -ne 0) { throw "git push failed with exit code $LASTEXITCODE" }
	Write-Host "Pushed."
}
else {
	Write-Host "Dry run (no push). Re-run with -Push to publish."
	Write-Host "Work tree left at: $WorkDir"
}

Write-Host ""
Write-Host "Proxmox one-liner:"
Write-Host ('  bash -c "$(curl -fsSL {0}/proxmox/myoffice.sh)"' -f $repoRawBase)
Write-Host ""
