# CheckLocalGitStatus
# 
# Verifica di un set di repo GIT locali rispetto al server origin remoto
# per stabilire quali necessitino di aggiornamento
#
# esempio chiamata: 

# parametri in ingresso
param (
    [string]$RootPath = "C:\Users\samuele.steamw\source",  # Default alla cartella dei sorgenti, da passare invocando il comando
    [switch]$SwitchToMain,
    [string]$OutputFile = "$PSScriptRoot\outdated_repos.txt",
    [switch]$Help
)


# Mostra help message se --help or -h passato come argomento
if ($Help -or $args -contains "--help" -or $args -contains "-h") {
    Write-Host @"
Usage: .\Check-GitRepos.ps1 [-RootPath <path>] [-SwitchToMain] [-OutputFile <file>] [--help]

Checks all Git repositories under the specified folder and compares their main/master branch
with the remote origin. Optionally switches to main/master to perform the check.

Parameters:
  -RootPath       Path to the root folder containing Git repositories (default: current script path)
  -SwitchToMain   Temporarily switch to main/master branch to perform the check
  -OutputFile     Path to the output file listing outdated repositories
  --help, -h      Show this help message

Examples:
  .\Check-GitRepos.ps1 -RootPath "D:\Dev\Projects"
  .\Check-GitRepos.ps1 -SwitchToMain
  .\Check-GitRepos.ps1 -RootPath "C:\Code" -SwitchToMain -OutputFile "C:\outdated.txt"
"@ -ForegroundColor Cyan
    exit
}

$branchesToCheck = @("main", "master")
$outdatedRepos = @()

# Function to check Git status
function Check-GitStatus {
    param (
        [string]$repoPath
    )

    Write-Host "`nChecking repository at: $repoPath" -ForegroundColor Cyan
    Push-Location $repoPath

    if (-not (Test-Path ".git")) {
        Write-Host "Not a Git repository." -ForegroundColor Yellow
        Pop-Location
        return
    }

    git fetch origin *> $null 2>&1

    $originalBranch = git rev-parse --abbrev-ref HEAD 2>$null

    # Check which of 'main' or 'master' exists on the remote
    $remoteBranches = git ls-remote --heads origin | ForEach-Object {
        ($_ -split "\s+")[1] -replace "refs/heads/", ""
    }

    $targetBranch = $branchesToCheck | Where-Object { $remoteBranches -contains $_ } | Select-Object -First 1

    if (-not $targetBranch) {
        Write-Host "No 'main' or 'master' branch found on remote." -ForegroundColor Red
        Pop-Location
        return
    }

    if ($SwitchToMain -and $originalBranch -ne $targetBranch) {
        git stash push -u -m "Temp stash before switching branches" *> $null 2>&1
        git checkout $targetBranch *> $null 2>&1
    }

    $status = git status -sb 2>$null
    $aheadBehind = git rev-list --left-right --count origin/$targetBranch...HEAD 2>$null

    if ($aheadBehind) {
        $parts = $aheadBehind -split "`t"
        $behind = [int]$parts[0]
        $ahead = [int]$parts[1]

        if ($ahead -gt 0 -or $behind -gt 0) {
            Write-Host "🔺 Repo is not up to date with origin/$targetBranch (ahead: $ahead, behind: $behind)" -ForegroundColor Yellow
            $outdatedRepos += $repoPath
        } else {
            Write-Host "✅ Repo is up to date with origin/$targetBranch" -ForegroundColor Green
        }
    }

    if ($SwitchToMain -and $originalBranch -ne $targetBranch) {
        git checkout $originalBranch *> $null 2>&1
        git stash pop *> $null 2>&1
    }

    Pop-Location
}

# Get all subdirectories containing .git folders
$repos = Get-ChildItem -Path $RootPath -Recurse -Directory | Where-Object {
    Test-Path "$($_.FullName)\.git"
}

# Check each repository
foreach ($repo in $repos) {
    Check-GitStatus -repoPath $repo.FullName
}

# Output outdated repos to file
if ($outdatedRepos.Count -gt 0) {
    "`n📄 Outdated repositories:" | Out-File -FilePath $OutputFile -Encoding UTF8
    foreach ($repo in $outdatedRepos) {
        $repo | Tee-Object -FilePath $OutputFile -Append
    }
    Write-Host "`n📄 Outdated repositories saved to: $OutputFile" -ForegroundColor Cyan
} else {
    "All repositories are up to date!" | Out-File -FilePath $OutputFile -Encoding UTF8
    Write-Host "`n🎉 All repositories are up to date!" -ForegroundColor Green
}
