@echo off
setlocal EnableExtensions EnableDelayedExpansion

rem One-time AnyDesk unattended access setup for market computers.
rem AnyDesk --start-service / --stop-service Windows'ta yonetici ister; aksi halde
rem "Can not start/stop the service. Elevation required." hatasi gorunur.
rem Calistirma: sag tik "Yonetici olarak calistir" VEYA asagidaki otomatik UAC.

set "SCRIPT_DIR=%~dp0"
set "LOG_DIR=%SCRIPT_DIR%..\Log"
set "LOG_FILE=%LOG_DIR%\AnyDeskMaintenance.log"
set "DONE_FILE=%SCRIPT_DIR%AnyDeskMaintenance.done"
set "FORCE_REINSTALL=0"
set "PROTECTED_ANYDESK_ID=1252392453"

if not exist "%LOG_DIR%" mkdir "%LOG_DIR%" >nul 2>&1

net session >nul 2>&1
if not errorlevel 1 goto :HaveAdmin
call :log "Yonetici degil; UAC ile yeniden baslatiliyor."
>"%TEMP%\%~n0_elev.vbs" echo Set sh=CreateObject^("Shell.Application"^)
>>"%TEMP%\%~n0_elev.vbs" echo sh.ShellExecute "%~s0", "%*", "", "runas", 1
cscript //nologo "%TEMP%\%~n0_elev.vbs"
del "%TEMP%\%~n0_elev.vbs" >nul 2>&1
exit /b 0

:HaveAdmin

call :log "Basladi."

if /i "%~1"=="--reinstall" (
    set "FORCE_REINSTALL=1"
    shift /1
)

set "ANYDESK_EXE="
set "CURRENT_ANYDESK_ID="

call :find_anydesk

if defined ANYDESK_EXE (
    for /f "usebackq tokens=* delims=" %%I in (`"%ANYDESK_EXE%" --get-id 2^>nul`) do set "CURRENT_ANYDESK_ID=%%I"
    set "CURRENT_ANYDESK_ID=!CURRENT_ANYDESK_ID: =!"
    if "!CURRENT_ANYDESK_ID!"=="%PROTECTED_ANYDESK_ID%" (
        call :log "Korumali merkez/admin AnyDesk ID bulundu. AnyDesk ayarlarina dokunulmayacak. ID=%PROTECTED_ANYDESK_ID%"
        echo Attempted=%DATE% %TIME%>"%DONE_FILE%"
        echo Status=ProtectedAdmin>>"%DONE_FILE%"
        echo AnyDeskId=%PROTECTED_ANYDESK_ID%>>"%DONE_FILE%"
        exit /b 0
    )
)

if exist "%DONE_FILE%" (
    call :validate_done_file
    if "!DONE_VALID!"=="1" (
        call :log "Tek seferlik islem daha once tamamlanmis ve cihaz ID ile uyumlu. Atlandi."
        exit /b 0
    )

    call :log "AnyDeskMaintenance.done mevcut ama bu cihaz icin gecersiz/eski. Silinip bakim yeniden calisacak."
    del /f /q "%DONE_FILE%" >nul 2>&1
)

if "%FORCE_REINSTALL%"=="1" if defined ANYDESK_EXE (
    call :stop_anydesk_for_reinstall
    call :log "AnyDesk reinstall istendi. Kaldirma deneniyor."
    "%ANYDESK_EXE%" --remove >nul 2>&1
    timeout /t 3 /nobreak >nul 2>&1
    set "ANYDESK_EXE="
)

if not defined ANYDESK_EXE (
    if exist "%SCRIPT_DIR%AnyDesk.exe" (
        call :log "AnyDesk yok. Tools\\AnyDesk.exe ile sessiz kurulum deneniyor."
        "%SCRIPT_DIR%AnyDesk.exe" --install "%ProgramFiles(x86)%\AnyDesk" --start-with-win --create-desktop-icon --silent >nul 2>&1
        timeout /t 3 /nobreak >nul 2>&1
        if exist "%ProgramFiles(x86)%\AnyDesk\AnyDesk.exe" "%ProgramFiles(x86)%\AnyDesk\AnyDesk.exe" --start-service >nul 2>&1
    ) else if exist "%SCRIPT_DIR%AnyDesk.msi" (
        call :log "AnyDesk yok. Tools\\AnyDesk.msi ile sessiz kurulum deneniyor."
        msiexec /i "%SCRIPT_DIR%AnyDesk.msi" /qn /norestart >nul 2>&1
        timeout /t 3 /nobreak >nul 2>&1
        if exist "%ProgramFiles(x86)%\AnyDesk\AnyDesk.exe" "%ProgramFiles(x86)%\AnyDesk\AnyDesk.exe" --start-service >nul 2>&1
    )
)

call :find_anydesk

if not defined ANYDESK_EXE (
    call :log "AnyDesk.exe bulunamadi ve kurulum dosyasi yok. Islem basarisiz."
    exit /b 1
)

call :start_anydesk_service_only

set "CURRENT_ANYDESK_ID="
for /f "usebackq tokens=* delims=" %%I in (`"%ANYDESK_EXE%" --get-id 2^>nul`) do set "CURRENT_ANYDESK_ID=%%I"
set "CURRENT_ANYDESK_ID=!CURRENT_ANYDESK_ID: =!"
if "!CURRENT_ANYDESK_ID!"=="%PROTECTED_ANYDESK_ID%" (
    call :log "Korumali merkez/admin AnyDesk ID bulundu. AnyDesk ayarlarina dokunulmayacak. ID=%PROTECTED_ANYDESK_ID%"
    echo Attempted=%DATE% %TIME%>"%DONE_FILE%"
    echo Status=ProtectedAdmin>>"%DONE_FILE%"
    echo AnyDeskId=%PROTECTED_ANYDESK_ID%>>"%DONE_FILE%"
    exit /b 0
)

set "AD_PASSWORD=%~1"
if not defined AD_PASSWORD (
    rem Varsayilan merkez AnyDesk parolasi. Guvenlik icin paketi sadece yetkili cihazlara dagitin.
    set "AD_PASSWORD=026012016h-"
)

if not defined AD_PASSWORD (
    call :log "Parola bos oldugu icin islem yapilmadi."
    exit /b 2
)

call :log "AnyDesk bulundu: %ANYDESK_EXE%"
call :log "Unattended access parolasi tek seferlik ayarlaniyor."

rem Remove-password komutlari modal yetki uyarisi gosterebildigi icin kullanilmiyor.
powershell -NoProfile -ExecutionPolicy Bypass -Command "$exe=$env:ANYDESK_EXE; $pwd=$env:AD_PASSWORD; $p=New-Object Diagnostics.Process; $p.StartInfo.FileName=$exe; $p.StartInfo.Arguments='--set-password _unattended_access'; $p.StartInfo.UseShellExecute=$false; $p.StartInfo.RedirectStandardInput=$true; $p.StartInfo.CreateNoWindow=$true; [void]$p.Start(); $p.StandardInput.Write($pwd); $p.StandardInput.Close(); if(-not $p.WaitForExit(20000)){ try{$p.Kill()}catch{}; exit 124 }; exit $p.ExitCode" >nul 2>&1
set "SET_PASSWORD_EXIT=%ERRORLEVEL%"
if not "%SET_PASSWORD_EXIT%"=="0" (
    call :log "Profil bazli set-password basarisiz oldu. Eski AnyDesk komutu deneniyor."
    powershell -NoProfile -ExecutionPolicy Bypass -Command "$exe=$env:ANYDESK_EXE; $pwd=$env:AD_PASSWORD; $p=New-Object Diagnostics.Process; $p.StartInfo.FileName=$exe; $p.StartInfo.Arguments='--set-password'; $p.StartInfo.UseShellExecute=$false; $p.StartInfo.RedirectStandardInput=$true; $p.StartInfo.CreateNoWindow=$true; [void]$p.Start(); $p.StandardInput.Write($pwd); $p.StandardInput.Close(); if(-not $p.WaitForExit(20000)){ try{$p.Kill()}catch{}; exit 124 }; exit $p.ExitCode" >nul 2>&1
    set "SET_PASSWORD_EXIT=%ERRORLEVEL%"
)

if not "%SET_PASSWORD_EXIT%"=="0" (
    call :log "AnyDesk parola ayarlanamadi. ExitCode=%SET_PASSWORD_EXIT%"
    call :start_anydesk_service_only
    exit /b %SET_PASSWORD_EXIT%
)

call :start_anydesk_service_only

echo Attempted=%DATE% %TIME%>"%DONE_FILE%"
echo Completed=%DATE% %TIME%>>"%DONE_FILE%"
if defined CURRENT_ANYDESK_ID echo AnyDeskId=%CURRENT_ANYDESK_ID%>>"%DONE_FILE%"
echo Status=PasswordSetOk>>"%DONE_FILE%"
call :log "AnyDesk unattended access parolasi ayarlandi. Tek seferlik marker yazildi."
exit /b 0

:find_anydesk
set "ANYDESK_EXE="
if exist "%ProgramFiles(x86)%\AnyDesk\AnyDesk.exe" set "ANYDESK_EXE=%ProgramFiles(x86)%\AnyDesk\AnyDesk.exe"
if not defined ANYDESK_EXE if exist "%ProgramFiles%\AnyDesk\AnyDesk.exe" set "ANYDESK_EXE=%ProgramFiles%\AnyDesk\AnyDesk.exe"
if not defined ANYDESK_EXE if exist "%LocalAppData%\Programs\AnyDesk\AnyDesk.exe" set "ANYDESK_EXE=%LocalAppData%\Programs\AnyDesk\AnyDesk.exe"
exit /b 0

:validate_done_file
set "DONE_VALID=0"
set "DONE_STATUS="
set "DONE_ANYDESK_ID="
for /f "usebackq tokens=1,* delims==" %%A in ("%DONE_FILE%") do (
    if /i "%%A"=="Status" set "DONE_STATUS=%%B"
    if /i "%%A"=="AnyDeskId" set "DONE_ANYDESK_ID=%%B"
)
set "DONE_STATUS=!DONE_STATUS: =!"
set "DONE_ANYDESK_ID=!DONE_ANYDESK_ID: =!"
if /i "!DONE_STATUS!"=="ProtectedAdmin" if "!CURRENT_ANYDESK_ID!"=="%PROTECTED_ANYDESK_ID%" set "DONE_VALID=1"
if /i "!DONE_STATUS!"=="PasswordSetOk" if defined CURRENT_ANYDESK_ID if defined DONE_ANYDESK_ID if "!CURRENT_ANYDESK_ID!"=="!DONE_ANYDESK_ID!" set "DONE_VALID=1"
exit /b 0

:stop_anydesk_for_reinstall
call :log "AnyDesk yeniden kurulum icin acik uygulama/servis durduruluyor."
if defined ANYDESK_EXE "%ANYDESK_EXE%" --stop-service >nul 2>&1
sc stop AnyDesk >nul 2>&1
powershell -NoProfile -ExecutionPolicy Bypass -Command "Get-Process AnyDesk -ErrorAction SilentlyContinue | Stop-Process -Force -ErrorAction SilentlyContinue" >nul 2>&1
timeout /t 2 /nobreak >nul 2>&1
exit /b 0

:start_anydesk_after_maintenance
call :log "AnyDesk bakimi sonrasi sadece servis baslatiliyor. UI acilmayacak."
if defined ANYDESK_EXE (
    "%ANYDESK_EXE%" --restart-service >nul 2>&1
    "%ANYDESK_EXE%" --start-service >nul 2>&1
) else if exist "%ProgramFiles(x86)%\AnyDesk\AnyDesk.exe" (
    "%ProgramFiles(x86)%\AnyDesk\AnyDesk.exe" --start-service >nul 2>&1
) else if exist "%ProgramFiles%\AnyDesk\AnyDesk.exe" (
    "%ProgramFiles%\AnyDesk\AnyDesk.exe" --start-service >nul 2>&1
)
exit /b 0

:start_anydesk_service_only
call :log "AnyDesk servis parola ayari icin baslatiliyor."
if defined ANYDESK_EXE "%ANYDESK_EXE%" --start-service >nul 2>&1
timeout /t 2 /nobreak >nul 2>&1
exit /b 0

:log
echo [%DATE% %TIME%] %~1>>"%LOG_FILE%"
exit /b 0
