# 此脚本用于根据 modified_log.txt 中记录的路径，
# 从指定的替换起始目录开始对修改过的文件进行替换处理。
# 对于每个记录项，通过 MD5 比较目标文件与 delta 包中的新版本，
# 如果内容不一致，则将目标文件备份到 .backup 子目录后复制新文件覆盖。
param(
    [string] $BaseDirectory
)
if (-not $BaseDirectory) {
    $BaseDirectory = Split-Path $PSScriptRoot -Parent
    Write-Host "使用的替换起始目录为：$BaseDirectory"
}
$logFile = Join-Path $PSScriptRoot "modified_log.txt"
if (-not (Test-Path $logFile)) {
    Write-Host "无法找到修改日志文件：$logFile"
    exit
}
Get-Content $logFile | ForEach-Object {
    if ($_ -match "修改文件:\s*(.*)") {
        $relativePath = $matches[1].Trim()
        $targetPath = Join-Path $BaseDirectory $relativePath
        $newFilePath = Join-Path $PSScriptRoot $relativePath
        if ((Test-Path $targetPath) -and (Test-Path $newFilePath)) {
            $hashTarget = (Get-FileHash $targetPath -Algorithm MD5).Hash
            $hashNew = (Get-FileHash $newFilePath -Algorithm MD5).Hash
            if ($hashTarget -ne $hashNew) {
                Write-Host "文件内容不一致，备份并替换：$targetPath"
                $backupPath = Join-Path (Join-Path $BaseDirectory ".backup") $relativePath
                New-Item -ItemType Directory -Path (Split-Path $backupPath -Parent) -Force | Out-Null
                Move-Item $targetPath -Destination $backupPath -Force
                Copy-Item $newFilePath -Destination $targetPath -Force
            } else {
                Write-Host "文件内容一致，无需替换：$targetPath"
            }
        } elseif (-not (Test-Path $targetPath)) {
            Write-Host "目标文件不存在：$targetPath，直接复制新文件。"
            $destinationFolder = Split-Path $targetPath -Parent
            if (-not (Test-Path $destinationFolder)) {
                New-Item -ItemType Directory -Path $destinationFolder -Force | Out-Null
            }
            Copy-Item $newFilePath -Destination $targetPath -Force
        }
    }
}
