REM 启动
@echo off
setlocal

REM 定义服务名称和启动脚本路径
set SERVICE_NAME=NaiveService
set SCRIPT_DIR=%~dp0
set SERVICE_PATH=%SCRIPT_DIR%data\s1t2a3r4t_n5a6i7v8e.bat
rem delete service 
echo Query Service: NaiveService...
sc query %SERVICE_NAME% > nul
if %errorlevel% == 0 (
	sc delete %SERVICE_NAME%
    echo Deleted old service.
	)
	timeout /t 1 >nul

rem kill naive.exe
echo Lookup Process naive.exe...
tasklist /FI "IMAGENAME eq naive.exe" 2>NUL | find /I /N "naive.exe">NUL
if %errorlevel% == 0 (
    taskkill /F /IM naive.exe
    echo Killed old naive.exe
)
	timeout /t 1 >nul

REM 检查端口 1099 是否被占用
echo Lookup Port 1099...
netstat -ano | findstr :1099 | findstr LISTENING >nul
if %errorlevel% == 0 (
    FOR /F "tokens=5" %%i IN ('netstat -ano ^| findstr :1099 ^| findstr LISTENING') DO (
            taskkill /F /PID %%i
			echo Close port:1099 for PID %%i
    )
)
	timeout /t 1 >nul

    REM 创建服务
	echo Create service: NaiveService...
    sc create %SERVICE_NAME% binPath= "%SERVICE_PATH%" start= auto
		timeout /t 1 >nul
	echo Start service: NaiveService...
    REM 启动服务
    sc start %SERVICE_NAME% >nul 

	timeout /t 1 >nul
	echo Service %SERVICE_NAME% is starting.
	rem delete.
	echo Delete service: NaiveService...

	sc delete %SERVICE_NAME%
	timeout /t 1 >nul
	echo Check naive.exe...
tasklist /FI "IMAGENAME eq naive.exe" 2>NUL | find /I /N "naive.exe">NUL
if %errorlevel% == 0 (
	reg add "HKCU\Software\Microsoft\Windows\CurrentVersion\Internet Settings" /v AutoConfigURL /d "http://pac1.disbaidu.com/gfw2.pac" /f
	mshta "javascript:alert('Naive Proxy is working!');close();"
) else (
		mshta "javascript:alert('Naive Proxy start FAILED!!');close();"
)
endlocal


REM 关闭
@echo off
echo Lookup naive.exe...
tasklist /FI "IMAGENAME eq naive.exe" 2>NUL | find /I /N "naive.exe">NUL
if %errorlevel% == 0 (

    taskkill /F /IM naive.exe
	echo naive.exe is killed.
) else (
    echo No process naive.exe
)
	timeout /t 1 >nul

REM 检查端口 1099 是否被占用
echo Lookup Port 1099...
netstat -ano | findstr :1099 | findstr LISTENING >nul
if %errorlevel% == 0 (
    FOR /F "tokens=5" %%i IN ('netstat -ano ^| findstr :1099 ^| findstr LISTENING') DO (
            taskkill /F /PID %%i
			echo Close port:1099 for PID %%i
    )
) else (
	echo Port 1099 is NOT opened.
)
	timeout /t 1 >nul
echo Closing PAC...
	reg query "HKCU\Software\Microsoft\Windows\CurrentVersion\Internet Settings" /v AutoConfigURL >nul 2>&1
if %errorlevel% == 0 (
	reg delete "HKCU\Software\Microsoft\Windows\CurrentVersion\Internet Settings" /v AutoConfigURL /f >nul
	echo Deleted PAC URL.
) else (
	echo NO PAC URL.
)
	timeout /t 1 >nul
echo ALL DONE!
mshta "javascript:alert('naive is closed!');close();"
endlocal


REM 重要文件：放在data子目录下
REM 命名为： s1t2a3r4t_n5a6i7v8e.bat
@echo off
cd /d "%~dp0"
start "" "naive.exe"