# 此脚本根据 deleted_log.txt 中的记录，
# 从 .unused 文件夹的父目录开始对删除项进行处理。
# 对于每个删除项，使用 MD5 比较 .unused 中的文件/目录与目标项，
# 若一致则直接删除；否则将目标项移动到 .backup 子目录中备份。
param(
    [string] $BaseDirectory
)
if (-not $BaseDirectory) {
    $BaseDirectory = Split-Path $PSScriptRoot -Parent
    Write-Host "使用的删除起始目录为：$BaseDirectory"
}
$logFile = Join-Path $PSScriptRoot "deleted_log.txt"
if (-not (Test-Path $logFile)) {
    Write-Host "无法找到日志文件：$logFile"
    exit
}
function Compare-FolderMD5 {
    param(
        [string] $Folder1,
        [string] $Folder2
    )
    $files1 = Get-ChildItem $Folder1 -Recurse -File
    foreach ($f1 in $files1) {
        $rel = $f1.FullName.Substring($Folder1.Length)
        $f2 = Join-Path $Folder2 $rel
        if (-not (Test-Path $f2)) {
            return $false
        }
        $hash1 = (Get-FileHash $f1.FullName -Algorithm MD5).Hash
        $hash2 = (Get-FileHash $f2 -Algorithm MD5).Hash
        if ($hash1 -ne $hash2) { return $false }
    }
    return $true
}
Get-Content $logFile | ForEach-Object {
    if ($_ -match "删除(?:文件|目录):\s*(.*)") {
        $relativePath = $matches[1].Trim()
        $targetPath = Join-Path $BaseDirectory $relativePath
        $unusedPath = Join-Path $PSScriptRoot $relativePath
        if (Test-Path $targetPath) {
            if ((Get-Item $targetPath).PSIsContainer) {
                if (Compare-FolderMD5 -Folder1 $targetPath -Folder2 $unusedPath) {
                    Write-Host "目录一致，删除：$targetPath"
                    Remove-Item $targetPath -Recurse -Force
                } else {
                    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
                }
            } else {
                $hashTarget = (Get-FileHash $targetPath -Algorithm MD5).Hash
                $hashUnused = (Get-FileHash $unusedPath -Algorithm MD5).Hash
                if ($hashTarget -eq $hashUnused) {
                    Write-Host "文件一致，删除：$targetPath"
                    Remove-Item $targetPath -Force
                } else {
                    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
                }
            }
        } else {
            Write-Host "目标路径不存在：$targetPath"
        }
    }
}
