@echo off
setlocal
chcp 65001 >nul
set "PAUSE=1"
if /i "%~1"=="--no-pause" set "PAUSE=0"
net session >nul 2>&1
if not "%errorlevel%"=="0" goto elevate
set "SELF=%~f0"
set "SRCCOPY=%TEMP%\cobweb-prep-src.txt"
set "BODY=%TEMP%\cobweb-prep-body.ps1"
copy /y "%SELF%" "%SRCCOPY%" >nul
powershell.exe -NoProfile -ExecutionPolicy Bypass -Command "$p='%SRCCOPY%'; $o='%BODY%'; $lines=[System.IO.File]::ReadAllLines($p,[System.Text.Encoding]::UTF8); $i=-1; for($k=0;$k -lt $lines.Count;$k++){ if($lines[$k].Trim() -eq '::POWERSHELL-BODY'){ $i=$k; break } }; if($i -lt 0){ Write-Host 'tool body missing'; exit 9 }; [System.IO.File]::WriteAllLines($o, $lines[($i+1)..($lines.Count-1)], (New-Object System.Text.UTF8Encoding($true)))"
if not "%errorlevel%"=="0" goto fail
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "%BODY%"
set "RC=%errorlevel%"
del "%SRCCOPY%" >nul 2>&1
del "%BODY%" >nul 2>&1
goto finish

:elevate
echo Requesting administrator privileges...
powershell.exe -NoProfile -Command "Start-Process -FilePath '%~f0' -Verb RunAs -ArgumentList '%1'"
exit /b 0

:fail
del "%SRCCOPY%" >nul 2>&1
set "RC=9"

:finish
if "%PAUSE%"=="0" exit /b %RC%
echo.
pause
exit /b %RC%

::POWERSHELL-BODY
$ErrorActionPreference = 'Continue'
$stamp = Get-Date -Format 'yyyyMMdd'
$pinDirName = "_update_quarantine_$stamp"
$problems = New-Object System.Collections.Generic.List[string]
$notes = New-Object System.Collections.Generic.List[string]

Write-Host '================================================'
Write-Host ' 小蜘蛛 · 客服机准备工具'
Write-Host ' 1) 把小蜘蛛加入杀毒信任'
Write-Host ' 2) 关闭微信自动升级（钉住限定版本）'
Write-Host ' 请在装好限定版微信并登录一次之后运行本工具。'
Write-Host '================================================'
Write-Host ('时间  : ' + (Get-Date -Format 'yyyy-MM-dd HH:mm:ss'))
Write-Host ('机器  : ' + $env:COMPUTERNAME)
Write-Host ('用户  : ' + $env:USERDOMAIN + '\' + $env:USERNAME)
Write-Host ''

Write-Host '[1] 杀毒信任'
$defenderActive = $false
try {
  $mp = Get-MpPreference -ErrorAction Stop
  $defenderActive = $true
  $paths = @(
    (Join-Path $env:USERPROFILE 'Downloads'),
    'C:\Program Files\CobwebWin',
    'C:\Program Files (x86)\CobwebWin',
    'C:\ProgramData\CobwebWin'
  )
  foreach ($p in $paths) {
    try {
      Add-MpPreference -ExclusionPath $p -ErrorAction Stop
      Write-Host ('      已信任目录: ' + $p)
    } catch {
      Write-Host ('      目录信任失败: ' + $p)
      [void]$problems.Add('Defender 目录信任失败 ' + $p)
    }
  }
  foreach ($proc in @('cobweb-win-agent.exe', 'cobweb-sidebar.exe', 'frpc.exe', 'sshd.exe')) {
    try {
      Add-MpPreference -ExclusionProcess $proc -ErrorAction Stop
      Write-Host ('      已信任进程: ' + $proc)
    } catch {
      Write-Host ('      进程信任失败: ' + $proc)
      [void]$problems.Add('Defender 进程信任失败 ' + $proc)
    }
  }
} catch {
  Write-Host '      Windows Defender 未接管本机（多为腾讯电脑管家/火绒/360 代管），本步跳过。'
  Write-Host '      请在那款安全软件里把下面目录和程序手动加为信任：'
  Write-Host '        目录: C:\Program Files (x86)\CobwebWin、C:\ProgramData\CobwebWin、下载文件夹'
  Write-Host '        程序: cobweb-win-agent.exe、cobweb-sidebar.exe、frpc.exe、sshd.exe'
  [void]$notes.Add('本机安全软件非 Defender，需手动加信任')
}
Write-Host ''

Write-Host '[2] 查找本机微信'
$roots = New-Object System.Collections.Generic.List[string]
if ($env:APPDATA) { [void]$roots.Add((Join-Path $env:APPDATA 'Tencent\xwechat')) }
Get-ChildItem 'C:\Users' -Directory -Force -ErrorAction SilentlyContinue | ForEach-Object {
  [void]$roots.Add((Join-Path $_.FullName 'AppData\Roaming\Tencent\xwechat'))
}
$roots = @($roots | Where-Object { Test-Path -LiteralPath $_ } | Sort-Object -Unique)

$installRoots = New-Object System.Collections.Generic.List[string]
foreach ($hive in @('HKCU:', 'HKLM:')) {
  foreach ($key in @('Software\Tencent\Weixin', 'Software\Tencent\WeChat', 'Software\WOW6432Node\Tencent\WeChat')) {
    $item = Get-ItemProperty ($hive + '\' + $key) -ErrorAction SilentlyContinue
    if ($item -and $item.InstallPath) { [void]$installRoots.Add([string]$item.InstallPath) }
  }
}
foreach ($p in @(
    'C:\Program Files\Tencent\Weixin',
    'C:\Program Files (x86)\Tencent\Weixin',
    'C:\Program Files\Tencent\WeChat',
    'C:\Program Files (x86)\Tencent\WeChat',
    (Join-Path $env:LOCALAPPDATA 'Programs\Weixin'),
    (Join-Path $env:LOCALAPPDATA 'Programs\WeChat'))) {
  [void]$installRoots.Add($p)
}
$installRoots = @($installRoots | Where-Object { $_ -and (Test-Path -LiteralPath $_) } | Sort-Object -Unique)

$versions = New-Object System.Collections.Generic.List[string]
foreach ($ir in $installRoots) {
  foreach ($exeName in @('Weixin.exe', 'WeChat.exe')) {
    $exePath = Join-Path $ir $exeName
    if (Test-Path -LiteralPath $exePath) {
      $ver = (Get-Item -LiteralPath $exePath).VersionInfo.ProductVersion
      if ($ver) { [void]$versions.Add($ver) }
    }
  }
  Get-ChildItem -LiteralPath $ir -Directory -Force -ErrorAction SilentlyContinue | ForEach-Object {
    if ($_.Name -match '^\d+\.\d+') { [void]$versions.Add($_.Name) }
  }
}
$versions = @($versions | Sort-Object -Unique)
if ($installRoots.Count -gt 0) {
  $installRoots | ForEach-Object { Write-Host ('      安装目录  : ' + $_) }
}
if ($versions.Count -gt 0) {
  $versions | ForEach-Object { Write-Host ('      已装版本  : ' + $_) }
} else {
  Write-Host '      未发现微信安装目录'
}
$running = @(Get-Process -Name Weixin, WeChat -ErrorAction SilentlyContinue | Where-Object { $_.Path })
if ($running.Count -gt 0) {
  $running | ForEach-Object {
    Write-Host ('      正在运行  : ' + (Get-Item -LiteralPath $_.Path).VersionInfo.ProductVersion)
  }
} else {
  Write-Host '      正在运行  : 微信当前未启动'
}
if ($roots.Count -eq 0) { Write-Host '      微信数据目录: 未发现（微信尚未登录过）' }
Write-Host ''

Write-Host '[3] 关闭微信自动升级'
$lockApplied = $false
if ($installRoots.Count -eq 0 -or $roots.Count -eq 0) {
  Write-Host '      跳过：本机还没有可锁定的微信。'
  Write-Host '      请先安装限定版本微信、打开并登录一次，然后重新运行本工具。'
  [void]$notes.Add('待办：装好微信并登录一次后，请再次运行本工具完成钉版')
} else {
  $lockApplied = $true
  foreach ($root in $roots) {
    $upd = Join-Path $root 'update'
    if (-not (Test-Path -LiteralPath $upd)) {
      Write-Host ('      无更新目录，跳过: ' + $root)
      continue
    }
    & icacls $upd /remove:d '*S-1-5-32-545' 2>&1 | Out-Null
    $pin = Join-Path $root $pinDirName
    foreach ($sub in @('download', 'patch')) {
      $src = Join-Path $upd $sub
      if (-not (Test-Path -LiteralPath $src)) { continue }
      $items = @(Get-ChildItem -LiteralPath $src -Force -ErrorAction SilentlyContinue)
      if ($items.Count -eq 0) { continue }
      $dest = Join-Path $pin $sub
      New-Item -ItemType Directory -Force -Path $dest | Out-Null
      $moved = 0
      foreach ($it in $items) {
        try {
          Move-Item -LiteralPath $it.FullName -Destination $dest -Force -ErrorAction Stop
          $moved++
        } catch {
          Write-Host ('      迁移失败: ' + $it.FullName)
          [void]$problems.Add('更新包迁移失败 ' + $it.FullName)
        }
      }
      Write-Host ('      已移走已下载更新包 ' + $moved + ' 项')
    }
    $stray = @(Get-ChildItem -LiteralPath $upd -Filter 'WeixinUpdate*.exe' -File -Force -ErrorAction SilentlyContinue)
    if ($stray.Count -gt 0) {
      $dest = Join-Path $pin '_updater'
      New-Item -ItemType Directory -Force -Path $dest | Out-Null
      foreach ($it in $stray) {
        try {
          Move-Item -LiteralPath $it.FullName -Destination $dest -Force -ErrorAction Stop
        } catch {
          Write-Host ('      迁移失败: ' + $it.FullName)
          [void]$problems.Add('更新程序迁移失败 ' + $it.FullName)
        }
      }
      Write-Host ('      已移走更新程序 ' + $stray.Count + ' 个')
    }
  }
  $disabled = 0
  foreach ($ir in $installRoots) {
    $found = @(Get-ChildItem -LiteralPath $ir -Recurse -Filter 'WeixinUpdate.exe' -File -Force -ErrorAction SilentlyContinue)
    foreach ($f in $found) {
      try {
        Rename-Item -LiteralPath $f.FullName -NewName ($f.Name + '.disabled-' + $stamp) -ErrorAction Stop
        Write-Host ('      已停用更新程序: ' + $f.FullName)
        $disabled++
      } catch {
        Write-Host ('      停用失败: ' + $f.FullName)
        [void]$problems.Add('更新程序停用失败 ' + $f.FullName)
      }
    }
  }
  if ($disabled -eq 0) { Write-Host '      更新程序此前已停用' }
  foreach ($root in $roots) {
    $upd = Join-Path $root 'update'
    if (-not (Test-Path -LiteralPath $upd)) { continue }
    $out = & icacls $upd /deny '*S-1-5-32-545:(OI)(CI)(WD,AD,WEA,WA)' 2>&1
    if ($LASTEXITCODE -ne 0) {
      Write-Host ('      更新目录拒写设置失败: ' + $upd)
      Write-Host ('        ' + ($out -join ' '))
      [void]$problems.Add('更新目录拒写失败 ' + $upd)
    } else {
      Write-Host ('      已对更新目录拒写: ' + $upd)
    }
  }
}
Write-Host ''

Write-Host '[4] 自检'
if ($lockApplied) {
  foreach ($root in $roots) {
    $upd = Join-Path $root 'update'
    if (-not (Test-Path -LiteralPath $upd)) { continue }
    $probe = Join-Path $upd 'cobweb_lock_probe.tmp'
    $blocked = $false
    try { Set-Content -LiteralPath $probe -Value 'x' -ErrorAction Stop } catch { $blocked = $true }
    if (-not $blocked) {
      Remove-Item -LiteralPath $probe -Force -ErrorAction SilentlyContinue
      Write-Host ('      更新目录仍可写入: ' + $upd)
      [void]$problems.Add('更新目录仍可写入 ' + $upd)
    } else {
      Write-Host '      更新目录写入被拒: 通过'
    }
  }
  $leftUpdater = @()
  foreach ($ir in $installRoots) {
    $leftUpdater += @(Get-ChildItem -LiteralPath $ir -Recurse -Filter 'WeixinUpdate.exe' -File -Force -ErrorAction SilentlyContinue)
  }
  if ($leftUpdater.Count -gt 0) {
    Write-Host ('      仍有更新程序可用: ' + (($leftUpdater | ForEach-Object { $_.FullName }) -join '; '))
    [void]$problems.Add('仍有更新程序未停用')
  } else {
    Write-Host '      更新程序已全部停用: 通过'
  }
  Write-Host '      微信不会被自动升级；重装或升级微信后需重新运行本工具。'
} else {
  Write-Host '      微信钉版尚未执行，安装微信后再运行本工具即可。'
}
Write-Host ''
foreach ($n in $notes) { Write-Host ('注意  : ' + $n) }
if ($problems.Count -eq 0) {
  Write-Host '结果: 通过。'
  if ($defenderActive) { Write-Host '      小蜘蛛已在 Windows Defender 信任名单内。' }
  exit 0
}
Write-Host ('结果: 有 ' + $problems.Count + ' 项未完成，请把上面输出发给技术同事。')
$problems | ForEach-Object { Write-Host ('      - ' + $_) }
exit 1
