@echo off
chcp 936 >nul
setlocal
title 班级叫号 · 电脑端开机自启修复

set "PS1=%TEMP%\classcall-autostart.ps1"
set "SELFDIR=%~dp0"
if "%SELFDIR:~-1%"=="\" set "SELFDIR=%SELFDIR:~0,-1%"

echo ===============================================
echo   班级叫号 · 电脑端开机自启修复
echo ===============================================
echo.

powershell -NoProfile -ExecutionPolicy Bypass -Command "$c=[IO.File]::ReadAllText('%~f0',[Text.Encoding]::GetEncoding(936));$m1='#PS'+'-BEGIN';$m2='#PS'+'-END';$a=$c.IndexOf($m1);$b=$c.IndexOf($m2);if(($a -lt 0) -or ($b -lt 0)){exit 1};[IO.File]::WriteAllText('%PS1%',$c.Substring($a+$m1.Length,$b-$a-$m1.Length),[Text.Encoding]::UTF8)"

if not exist "%PS1%" goto :nofile

fltmc >nul 2>&1
if errorlevel 1 goto :elevate

powershell -NoProfile -ExecutionPolicy Bypass -File "%PS1%" -Root "%SELFDIR%" -BatPath "%~f0" -HolderUser "%USERNAME%" -HolderDomain "%USERDOMAIN%"
if errorlevel 1 pause
goto :end

:elevate
echo 需要管理员权限，正在申请提权，请在弹窗里点「是」。
echo 如果点了「否」，修复不会生效，可以重新双击本文件。
echo.
set "LAUNCH=%TEMP%\classcall-autostart-launch.cmd"
> "%LAUNCH%" echo @echo off
>> "%LAUNCH%" echo powershell -NoProfile -ExecutionPolicy Bypass -File "%PS1%" -Root "%SELFDIR%" -BatPath "%~f0" -HolderUser "%USERNAME%" -HolderDomain "%USERDOMAIN%"
>> "%LAUNCH%" echo ping -n 3 127.0.0.1 ^>nul
>> "%LAUNCH%" echo del /q "%PS1%" ^>nul 2^>nul
>> "%LAUNCH%" echo del /q "%LAUNCH%" ^>nul 2^>nul
powershell -NoProfile -Command "Start-Process -FilePath '%LAUNCH%' -Verb RunAs"
goto :end

:nofile
echo [错误] 脚本释放失败，请重新下载本文件再运行。
pause
exit /b 1

:end
exit /b 0

#PS-BEGINparam(
    [string]$Root = "",
    [string]$BatPath = "",
    [string]$HolderUser = "",
    [string]$HolderDomain = ""
)

$ErrorActionPreference = "Continue"
$StateDir = Join-Path $env:ProgramData "ClassCall"
$RunKey = "HKCU:\Software\Microsoft\Windows\CurrentVersion\Run"
$TaskName = "ClassCall-PC"
$WatchTaskName = "ClassCall-PC-Watch"
$Wscript = Join-Path $env:SystemRoot "System32\wscript.exe"
$Self = $MyInvocation.MyCommand.Path
$Ansi = [System.Text.Encoding]::GetEncoding(0)
$Problem = 0

function Show-Step([string]$t) {
    Write-Host ""
    Write-Host ("[步骤] " + $t) -ForegroundColor Cyan
}
function Show-Ok([string]$t) {
    Write-Host ("   [OK] " + $t) -ForegroundColor Green
}
function Show-No([string]$t) {
    Write-Host ("   [!!] " + $t) -ForegroundColor Red
    $script:Problem = $script:Problem + 1
}
function Show-Note([string]$t) {
    Write-Host ("        " + $t) -ForegroundColor Gray
}
function Test-Admin {
    $id = [Security.Principal.WindowsIdentity]::GetCurrent()
    $pr = New-Object Security.Principal.WindowsPrincipal($id)
    return $pr.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
}
function Test-AppDir([string]$p) {
    if ([string]::IsNullOrWhiteSpace($p)) { return $false }
    try {
        if (-not (Test-Path -LiteralPath $p -PathType Container)) { return $false }
        if (-not (Test-Path -LiteralPath (Join-Path $p "main.js") -PathType Leaf)) { return $false }
        if (-not (Test-Path -LiteralPath (Join-Path $p "preload.js") -PathType Leaf)) { return $false }
        return $true
    } catch { return $false }
}
function Search-Tree([string]$top, [int]$deep) {
    if (-not $top) { return "" }
    if (-not (Test-Path -LiteralPath $top)) { return "" }
    $hit = Get-ChildItem -LiteralPath $top -Filter "main.js" -File -Recurse -Depth $deep -ErrorAction SilentlyContinue |
        Where-Object { $_.FullName -notmatch "\\Windows\\" } |
        Where-Object { Test-AppDir $_.DirectoryName } |
        Select-Object -First 1
    if ($hit) { return $hit.DirectoryName }
    return ""
}
function Unlock-Dir([string]$Path) {
    if (-not (Test-Path -LiteralPath $Path)) { return }
    try {
        $acl = Get-Acl -LiteralPath $Path
        $removed = 0
        foreach ($ace in @($acl.Access)) {
            if (($ace.AccessControlType -eq "Deny") -and (-not $ace.IsInherited)) {
                $acl.RemoveAccessRuleSpecific($ace) | Out-Null
                $removed = $removed + 1
            }
        }
        if ($removed -gt 0) { Set-Acl -LiteralPath $Path -AclObject $acl }
    } catch { Show-Note "解除写入限制失败，继续尝试写入" }
}
function Lock-Dir([string]$Path) {
    try {
        $acl = Get-Acl -LiteralPath $Path
        $sid = New-Object System.Security.Principal.SecurityIdentifier("S-1-5-32-545")
        $rule = New-Object System.Security.AccessControl.FileSystemAccessRule(
            $sid,
            [System.Security.AccessControl.FileSystemRights]"WriteData, AppendData, WriteExtendedAttributes, WriteAttributes, Delete, DeleteSubdirectoriesAndFiles",
            [System.Security.AccessControl.InheritanceFlags]"ContainerInherit, ObjectInherit",
            [System.Security.AccessControl.PropagationFlags]"None",
            [System.Security.AccessControl.AccessControlType]"Deny")
        $acl.AddAccessRule($rule)
        Set-Acl -LiteralPath $Path -AclObject $acl
        return $true
    } catch { return $false }
}
function Get-AppProcs {
    try {
        $all = @(Get-CimInstance -Query "select ProcessId,ExecutablePath,CommandLine from Win32_Process" -ErrorAction SilentlyContinue)
    } catch { return @() }
    $found = @()
    foreach ($pr in $all) {
        if ($pr.ExecutablePath) {
            if (($pr.ExecutablePath -eq $Exe) -or ($pr.ExecutablePath -eq $ExeFull)) { $found = $found + $pr; continue }
        }
        if ($pr.CommandLine -and ($pr.CommandLine -like "*classcall-pc*")) { $found = $found + $pr }
    }
    return $found
}

if (-not (Test-Admin)) {
    Write-Host "需要管理员权限。请右键本文件，选择「以管理员身份运行」。" -ForegroundColor Red
    exit 1
}

$currentName = [Security.Principal.WindowsIdentity]::GetCurrent().Name
$userName = $currentName
$accountNote = ""
if ($HolderUser) {
    $hd = $HolderDomain
    if (-not $hd) { $hd = $env:COMPUTERNAME }
    $holderFull = $hd + "\" + $HolderUser
    if ($holderFull -ne $currentName) {
        $sid = ""
        try {
            $sid = (New-Object System.Security.Principal.NTAccount($holderFull)).Translate([System.Security.Principal.SecurityIdentifier]).Value
        } catch { $sid = "" }
        if ($sid) {
            $hive = "Registry::HKEY_USERS\" + $sid + "\Software\Microsoft\Windows\CurrentVersion\Run"
            if (Test-Path -LiteralPath $hive) {
                $userName = $holderFull
                $RunKey = $hive
                $accountNote = "自启装到你平时登录的账户：" + $holderFull
            } else {
                $accountNote = "读不到 " + $holderFull + " 的注册表，自启只能装到当前管理员账户"
            }
        } else {
            $accountNote = "找不到账户 " + $holderFull + "，自启只能装到当前管理员账户"
        }
    }
}

Write-Host "正在查找教室端程序文件夹，可能需要十几秒..." -ForegroundColor Cyan

$AppDir = ""
$hints = New-Object System.Collections.ArrayList
if ($Root) { [void]$hints.Add($Root) }
if ($BatPath) { [void]$hints.Add((Split-Path -Parent $BatPath)) }
$oldCmd = Join-Path $StateDir "start-app.cmd"
if (Test-Path -LiteralPath $oldCmd -PathType Leaf) {
    $m = Select-String -LiteralPath $oldCmd -Pattern 'cd /d\s+"([^"]+)"' -ErrorAction SilentlyContinue | Select-Object -First 1
    if ($m) { [void]$hints.Add($m.Matches[0].Groups[1].Value) }
}
foreach ($h in $hints) {
    if (Test-AppDir $h) { $AppDir = (Resolve-Path -LiteralPath $h).Path; break }
}

if (-not $AppDir) {
    $tops = New-Object System.Collections.ArrayList
    foreach ($k in @("Desktop","Downloads","MyDocuments","UserProfile","ProgramFiles","ProgramFilesX86","CommonProgramFiles","CommonApplicationData","ApplicationData","LocalApplicationData")) {
        $p = ""
        try { $p = [Environment]::GetFolderPath($k) } catch { $p = "" }
        if ($p -and (-not $tops.Contains($p))) { [void]$tops.Add($p) }
    }
    foreach ($t in $tops) {
        $AppDir = Search-Tree $t 3
        if ($AppDir) { break }
    }
    if (-not $AppDir) {
        foreach ($d in @("D","E","F","G","H")) {
            $AppDir = Search-Tree ($d + ":\") 2
            if ($AppDir) { break }
        }
    }
}

if (-not $AppDir) {
    Write-Host ""
    Write-Host "[失败] 没找到教室端程序文件夹。" -ForegroundColor Red
    Show-Note "那个文件夹里应该有 main.js、preload.js、启动电脑端.bat"
    Write-Host "       请把本文件复制到那个文件夹里，再双击运行。" -ForegroundColor Yellow
    Write-Host ""
    Read-Host "按回车键关闭"
    exit 2
}

Write-Host ("   找到程序目录：" + $AppDir) -ForegroundColor Gray

$Exe = ""
$AppArg = ""
$isDev = $false
$pkg = Get-ChildItem -LiteralPath $AppDir -Filter "*.exe" -File -ErrorAction SilentlyContinue |
    Where-Object { $_.Name -match "班级叫号|ClassCall" } | Select-Object -First 1
if ($pkg) {
    $Exe = $pkg.FullName
} else {
    $cand = Join-Path $AppDir "node_modules\electron\dist\electron.exe"
    if (Test-Path -LiteralPath $cand -PathType Leaf) {
        $Exe = (Resolve-Path -LiteralPath $cand).Path
        $isDev = $true
    }
}
if (-not $Exe) {
    Write-Host ""
    Write-Host "[失败] 程序文件夹不完整，缺少可执行程序。" -ForegroundColor Red
    Show-Note "缺少 node_modules\electron\dist\electron.exe"
    Write-Host "       请重新解压电脑端压缩包，再运行本文件。" -ForegroundColor Yellow
    Write-Host ""
    Read-Host "按回车键关闭"
    exit 3
}

$ExeFull = $Exe
$LaunchDir = $AppDir
if ($isDev) { $AppArg = '"' + $LaunchDir + '" ' }
if (($AppDir -match "[^\x00-\x7F]") -or ($Exe -match "[^\x00-\x7F]")) {
    try {
        $fso = New-Object -ComObject Scripting.FileSystemObject
        $shortExe = $fso.GetFile($Exe).ShortPath
        $shortDir = $fso.GetFolder($AppDir).ShortPath
        if ($shortExe -and $shortDir -and ($shortExe -notmatch "[^\x00-\x7F]") -and ($shortDir -notmatch "[^\x00-\x7F]")) {
            $Exe = $shortExe
            $LaunchDir = $shortDir
            if ($isDev) { $AppArg = '"' + $LaunchDir + '" ' }
        }
    } catch { }
}

$startCmd = Join-Path $StateDir "start-app.cmd"
$startVbs = Join-Path $StateDir "start-app.vbs"
$watchVbs = Join-Path $StateDir "watch-app.vbs"

Write-Host ("   自启账户：" + $userName) -ForegroundColor Gray
if ($accountNote) { Write-Host ("   " + $accountNote) -ForegroundColor Yellow }

Show-Step "1/5 生成启动脚本"

try { New-Item -ItemType Directory -Force -Path $StateDir | Out-Null } catch { }
Unlock-Dir $StateDir

$cmdText = @"
@echo off
cd /d "$LaunchDir"
start "" "$Exe" ${AppArg}--hidden --profile="%APPDATA%\classcall-pc"
exit /b 0
"@
$vbsText = @"
Set sh = CreateObject("WScript.Shell")
sh.Run """$startCmd""", 0, False
"@
$watchText = @"
On Error Resume Next
Set sh = CreateObject("WScript.Shell")
Set wmi = GetObject("winmgmts:\\.\root\cimv2")
Set list = wmi.ExecQuery("select ProcessId from Win32_Process where CommandLine like '%classcall-pc%'")
If list.Count = 0 Then sh.Run """$startVbs""", 0, False
"@

$writeOk = $false
try {
    [System.IO.File]::WriteAllText($startCmd, $cmdText, $Ansi)
    [System.IO.File]::WriteAllText($startVbs, $vbsText, $Ansi)
    [System.IO.File]::WriteAllText($watchVbs, $watchText, $Ansi)
    $writeOk = $true
    Show-Ok ("已生成：" + $startCmd)
    Show-Ok ("已生成：" + $startVbs)
    Show-Ok ("已生成：" + $watchVbs)
} catch {
    Show-No ("写入脚本失败：" + $_.Exception.Message)
}

Show-Step "2/5 写入开机自启项"

$runOk = $false
if ($writeOk) {
    $runValue = '"' + $Wscript + '" //nologo //B "' + $startVbs + '"'
    try {
        New-Item -Path $RunKey -Force -ErrorAction SilentlyContinue | Out-Null
        New-ItemProperty -Path $RunKey -Name "ClassCall" -Value $runValue -PropertyType String -Force -ErrorAction Stop | Out-Null
        $check = (Get-ItemProperty -Path $RunKey -Name "ClassCall" -ErrorAction Stop).ClassCall
        if ($check) { $runOk = $true; Show-Ok "开机自启项已写入（登录后静默启动，无窗口）" }
        else { Show-No "开机自启项写进去了，但读不回来" }
    } catch { Show-No ("开机自启项写入失败：" + $_.Exception.Message) }
} else {
    Show-No "脚本没写成功，跳过开机自启项"
}

Show-Step "3/5 注册登录任务与掉线守护"

$taskOk = $false
$watchOk = $false
if ($writeOk) {
    try {
        $a1 = New-ScheduledTaskAction -Execute $Wscript -Argument ('//nologo //B "' + $startVbs + '"') -WorkingDirectory $StateDir
        $t1 = New-ScheduledTaskTrigger -AtLogOn -User $userName
        $s1 = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -StartWhenAvailable -MultipleInstances IgnoreNew -ExecutionTimeLimit ([TimeSpan]::Zero)
        $p1 = New-ScheduledTaskPrincipal -UserId $userName -LogonType Interactive -RunLevel Limited
        Register-ScheduledTask -TaskName $TaskName -Action $a1 -Trigger $t1 -Settings $s1 -Principal $p1 -Force -ErrorAction Stop | Out-Null
        $taskOk = $true
        Show-Ok ("已注册：" + $TaskName + "（登录 Windows 时启动）")
    } catch { Show-No ("登录任务注册失败：" + $_.Exception.Message) }

    try {
        $a2 = New-ScheduledTaskAction -Execute $Wscript -Argument ('//nologo //B "' + $watchVbs + '"') -WorkingDirectory $StateDir
        $t2 = New-ScheduledTaskTrigger -Once -At (Get-Date).AddMinutes(2) -RepetitionInterval (New-TimeSpan -Minutes 3) -RepetitionDuration (New-TimeSpan -Days 3650)
        $s2 = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -StartWhenAvailable -MultipleInstances IgnoreNew -ExecutionTimeLimit ([TimeSpan]::Zero)
        $p2 = New-ScheduledTaskPrincipal -UserId $userName -LogonType Interactive -RunLevel Limited
        Register-ScheduledTask -TaskName $WatchTaskName -Action $a2 -Trigger $t2 -Settings $s2 -Principal $p2 -Force -ErrorAction Stop | Out-Null
        $watchOk = $true
        Show-Ok ("已注册：" + $WatchTaskName + "（每 3 分钟检查一次，掉了自动拉起）")
    } catch { Show-No ("掉线守护注册失败：" + $_.Exception.Message) }
} else {
    Show-No "脚本没写成功，跳过任务注册"
}

Show-Step "4/5 锁定脚本目录"

$lockOk = $false
if ($writeOk) {
    $lockOk = Lock-Dir $StateDir
    if ($lockOk) { Show-Ok ("已锁定：" + $StateDir + "（能运行，不能改、不能删）") }
    else { Show-Note "锁定跳过，不影响开机自启" }
}

Show-Step "5/5 重启教室端并自检"

$oldIds = @()
foreach ($pr in (Get-AppProcs)) { $oldIds = $oldIds + $pr.ProcessId }
$closed = 0
foreach ($pr in (Get-AppProcs)) {
    try { Stop-Process -Id $pr.ProcessId -Force -ErrorAction Stop; $closed = $closed + 1 } catch { }
}
if ($closed -gt 0) {
    Show-Ok ("已关闭 " + $closed + " 个旧进程（手机端会自动重连）")
    Start-Sleep -Milliseconds 1200
}

$started = $false
if ($taskOk) {
    try { Start-ScheduledTask -TaskName $TaskName -ErrorAction Stop; $started = $true } catch { }
}
if (-not $started) {
    try {
        Start-Process -FilePath $Wscript -ArgumentList ('//nologo //B "' + $startVbs + '"') -WindowStyle Hidden
        $started = $true
    } catch { Show-No ("启动失败：" + $_.Exception.Message) }
}

$alive = $false
for ($i = 0; $i -lt 20; $i++) {
    Start-Sleep -Milliseconds 800
    foreach ($pr in (Get-AppProcs)) {
        if ($oldIds -notcontains $pr.ProcessId) { $alive = $true }
    }
    if ($alive) { break }
}
if ($alive) { Show-Ok "教室端已在后台运行（右下角托盘里，没有窗口）" }
else { Show-No "启动后没检测到新的进程，请重启电脑再看一次" }

Write-Host ""
Write-Host "================== 自检结果 ==================" -ForegroundColor Cyan
Write-Host ("  程序目录  ：" + $AppDir)
Write-Host ("  启动程序  ：" + $Exe)
Write-Host ("  运行账户  ：" + $userName)
Write-Host ("  开机自启项：" + $(if ($runOk) { "已写入" } else { "未写入" }))
Write-Host ("  登录任务  ：" + $(if ($taskOk) { "已注册" } else { "未注册" }))
Write-Host ("  掉线守护  ：" + $(if ($watchOk) { "已注册" } else { "未注册" }))
Write-Host ("  脚本目录  ：" + $(if ($lockOk) { "已锁定" } else { "未锁定" }))
Write-Host ("  当前状态  ：" + $(if ($alive) { "后台运行中" } else { "未检测到" }))
Write-Host "=============================================" -ForegroundColor Cyan
Write-Host ""
Show-Note "程序自己也会注册一条自启（electron.app.Electron），两条同时存在不会冲突。"
Show-Note "因为程序是单实例的，多出来的那条会自己退出。"

if ($Problem -eq 0) {
    Write-Host "全部完成。以后登录 Windows 会自动静默启动，不用再点任何东西。" -ForegroundColor Green
    Write-Host "这个修复文件可以删掉，也可以留着，以后电脑显示离线时再运行一次。" -ForegroundColor Green
} else {
    Write-Host "有步骤没成功，本文件保留在原处，可以再运行一次。" -ForegroundColor Yellow
    Show-Note ("本文件位置：" + $BatPath)
}

Write-Host ""
Read-Host "按回车键关闭" | Out-Null

$helper = Join-Path $env:TEMP ("cc-clean-" + $PID + ".cmd")
$helperText = @"
@echo off
ping -n 3 127.0.0.1 >nul
del /f /q "$Self" >nul 2>nul
(goto) 2>nul & del /f /q "%~f0"
"@
try {
    [System.IO.File]::WriteAllText($helper, $helperText, $Ansi)
    Start-Process -FilePath (Join-Path $env:SystemRoot "System32\cmd.exe") -ArgumentList ('/c "' + $helper + '"') -WindowStyle Hidden
} catch { }
exit 0

#PS-END
