# Git多仓库同步脚本 (PowerShell)
# 用于同步镜像仓库到你的个人仓库

param(
    [switch]$UseRebase = $false,
    [switch]$DryRun = $false
)

# 设置控制台编码以正确显示中文
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
$OutputEncoding = [System.Text.Encoding]::UTF8

# 设置Git配置以正确处理中文
$env:LC_ALL = "zh_CN.UTF-8"

function Write-ColorOutput {
    param(
        [string]$Message,
        [string]$Color = "White"
    )
    Write-Host $Message -ForegroundColor $Color
}

function Check-GitStatus {
    $status = git status --porcelain
    if ($status) {
        Write-ColorOutput "警告: 工作目录不干净，请先提交或储藏你的更改！" "Yellow"
        git status
        return $false
    }
    return $true
}

function Sync-Repositories {
    Write-ColorOutput "开始同步镜像仓库..." "Cyan"
    
    # 检查工作目录状态
    if (-not (Check-GitStatus)) {
        if (-not $DryRun) {
            return
        }
    }
    
    # 获取镜像仓库最新代码
    Write-ColorOutput "正在获取upstream最新代码..." "Green"
    if (-not $DryRun) {
        git fetch upstream
        if ($LASTEXITCODE -ne 0) {
            Write-ColorOutput "获取upstream代码失败！" "Red"
            return
        }
    } else {
        Write-ColorOutput "[预览模式] git fetch upstream" "Gray"
    }
    
    # 检查是否有新的提交
    $upstreamCommits = & git log HEAD..upstream/master --oneline | ForEach-Object { [System.Text.Encoding]::UTF8.GetString([System.Text.Encoding]::Default.GetBytes($_)) }
    if ($upstreamCommits) {
        Write-ColorOutput "发现镜像仓库有新的提交:" "Yellow"
        $upstreamCommits | ForEach-Object { Write-ColorOutput $_ "Gray" }
        
        if ($UseRebase) {
            Write-ColorOutput "正在使用rebase合并代码..." "Green"
            if (-not $DryRun) {
                git rebase upstream/master
                if ($LASTEXITCODE -ne 0) {
                    Write-ColorOutput "Rebase失败！请手动解决冲突后再继续。" "Red"
                    Write-ColorOutput "解决冲突后请运行: git rebase --continue" "Yellow"
                    return
                }
            } else {
                Write-ColorOutput "[预览模式] git rebase upstream/master" "Gray"
            }
        } else {
            Write-ColorOutput "正在使用merge合并代码..." "Green"
            if (-not $DryRun) {
                # 生成自动合并消息
                $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
                $mergeMessage = "feat: 同步上游仓库更新 ($timestamp)"
                
                git merge upstream/master --no-edit -m $mergeMessage
                if ($LASTEXITCODE -ne 0) {
                    Write-ColorOutput "Merge失败！请手动解决冲突后再继续。" "Red"
                    Write-ColorOutput "解决冲突后请运行: git commit" "Yellow"
                    return
                }
                Write-ColorOutput "使用自动合并消息: $mergeMessage" "Gray"
            } else {
                Write-ColorOutput "[预览模式] git merge upstream/master --no-edit -m '自动合并消息'" "Gray"
            }
        }
        
        Write-ColorOutput "同步完成！" "Green"
        Write-ColorOutput ""
        Write-ColorOutput "下一步操作提示:" "Cyan"
        Write-ColorOutput "   请手动推送到你的仓库: git push origin master" "White"
        if ($UseRebase) {
            Write-ColorOutput "   (如果使用了rebase，可能需要: git push origin master --force-with-lease)" "Yellow"
        }
        
    } else {
        Write-ColorOutput "镜像仓库没有新的提交，检查本地是否有未推送的修改..." "Blue"
        
        # 检查是否有本地修改需要推送
        $localCommits = & git log origin/master..HEAD --oneline | ForEach-Object { [System.Text.Encoding]::UTF8.GetString([System.Text.Encoding]::Default.GetBytes($_)) }
        if ($localCommits) {
            Write-ColorOutput "发现本地有未推送的修改:" "Yellow"
            $localCommits | ForEach-Object { Write-ColorOutput $_ "Gray" }
            
            Write-ColorOutput ""
            Write-ColorOutput "下一步操作提示:" "Cyan"
            Write-ColorOutput "   请手动推送到你的仓库: git push origin master" "White"
        } else {
            Write-ColorOutput "没有需要同步的内容。" "Blue"
        }
    }
}

function Show-Help {
    Write-ColorOutput "Git多仓库同步脚本" "Cyan"
    Write-ColorOutput "用法: .\sync-repos.ps1 [选项]" "White"
    Write-ColorOutput ""
    Write-ColorOutput "选项:" "Yellow"
    Write-ColorOutput "  -UseRebase    使用rebase代替merge进行合并" "White"
    Write-ColorOutput "  -DryRun       预览模式，不执行实际的git命令" "White"
    Write-ColorOutput "  -Help         显示此帮助信息" "White"
    Write-ColorOutput ""
    Write-ColorOutput "示例:" "Yellow"
    Write-ColorOutput "  .\sync-repos.ps1                # 使用merge同步" "White"
    Write-ColorOutput "  .\sync-repos.ps1 -UseRebase     # 使用rebase同步" "White"
    Write-ColorOutput "  .\sync-repos.ps1 -DryRun        # 预览模式" "White"
    Write-ColorOutput ""
    Write-ColorOutput "注意: 脚本不会自动推送到你的仓库，需要手动执行推送命令。" "Yellow"
}

# 主程序
if ($args -contains "-Help" -or $args -contains "--help" -or $args -contains "-h") {
    Show-Help
    return
}

Write-ColorOutput "Git多仓库同步工具" "Cyan"
Write-ColorOutput "===================" "Cyan"

# 显示当前配置
Write-ColorOutput "当前远程仓库配置:" "Blue"
git remote -v

Write-ColorOutput ""
if ($DryRun) {
    Write-ColorOutput "预览模式 - 不会执行实际的git命令" "Yellow"
}
if ($UseRebase) {
    Write-ColorOutput "使用rebase模式" "Yellow"
} else {
    Write-ColorOutput "使用merge模式" "Yellow"
}
Write-ColorOutput ""

Sync-Repositories

# 等待用户按键后再关闭
Write-ColorOutput ""
Write-ColorOutput "按任意键继续..." "Green"
$null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")