# Git Credential Configuration Script

param(
    [string]$Username = "",
    [string]$Email = "",
    [SecureString]$Password = $null,
    [switch]$Global = $false
)

# ========== Configure your username, email and password here ==========
$defaultUsername = "yichael"      # Change to your Git username
$defaultEmail = "2812319400@qq.com"  # Change to your Git email
$defaultPassword = "Qwerty123"      # Change to your Git password or access token
# ======================================================================

# Use default values if parameters not provided
if (-not $Username) { $Username = $defaultUsername }
if (-not $Email) { $Email = $defaultEmail }
if (-not $Password) {
    $Password = ConvertTo-SecureString $defaultPassword -AsPlainText -Force
}

# Get remote repository URL
$RemoteUrl = git config --get remote.origin.url 2>$null

# Convert SecureString to plain string (only when needed)
$passwordPlain = $null
if ($Password) {
    $BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($Password)
    $passwordPlain = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)
}

# Set Git configuration
$scope = if ($Global) { "--global" } else { "--local" }
$success = $true

if ($Username) {
    git config $scope user.name $Username 2>$null
    if ($LASTEXITCODE -ne 0) { $success = $false }
}

if ($Email) {
    git config $scope user.email $Email 2>$null
    if ($LASTEXITCODE -ne 0) { $success = $false }
}

# Clear old credentials
if ($RemoteUrl -and $RemoteUrl -match "https?://([^/]+)") {
    $domain = $Matches[1]
    cmdkey /delete:"LegacyGeneric:target=git:https://$domain" 2>$null | Out-Null
    git credential-cache exit 2>$null | Out-Null
}

# Set new credentials
if ($passwordPlain -and $RemoteUrl -and $RemoteUrl -match "https?://([^/]+)") {
    $domain = $Matches[1]
    $credentialInput = "protocol=https`nhost=$domain`nusername=$Username`npassword=$passwordPlain`n`n"
    $credentialInput | git credential approve 2>$null
    if ($LASTEXITCODE -ne 0) { $success = $false }
    # Clear plain password from memory
    [System.Runtime.InteropServices.Marshal]::ZeroFreeBSTR($BSTR)
    $passwordPlain = $null
}

# Show result
if ($success) {
    Write-Host "[OK] Configuration successful" -ForegroundColor Green
} else {
    Write-Host "[X] Configuration failed" -ForegroundColor Red
    exit 1
}
