@ECHO OFF
setlocal EnableExtensions EnableDelayedExpansion
pushd "%~dp0"

REM ==============================================================================
REM [EN] Enforce Windows 10 Classic Context Menu on Default User hive
REM [TR] Klasik Windows 10 sag tik menusunu Default User profilinde aktif et
REM ==============================================================================
reg load HKU\DefUser "C:\Users\Default\NTUSER.DAT" >nul 2>&1
reg add "HKU\DefUser\Software\Classes\CLSID\{86ca1aa0-34aa-4e8b-a509-50c905bae2a2}\InprocServer32" /f /ve >nul 2>&1
reg unload HKU\DefUser >nul 2>&1

REM ==============================================================================
REM [EN] Language detection and dynamic localization setup
REM [TR] Sistem dili algilama ve dinamik yerellestirme ayarlari
REM ==============================================================================
set ACTIVATION_STATUS=0
set "SYSLANG=0409"
for /f "tokens=3" %%a in ('reg query "HKLM\SYSTEM\CurrentControlSet\Control\Nls\Language" /v InstallLanguage 2^>nul') do set "SYSLANG=%%a"

set "ACT_FOLDER=Aktivasyon"
if /i "%SYSLANG%" == "041F" (
    set "TXT_TITLE=Windows Programlarinizi Yukluyor"
) else (
    set "TXT_TITLE=Windows is installing your programs"
)

REM ==============================================================================
REM [EN] Clean hosts file block entries if present (NTLite NdupSetup / NTLNDUP)
REM [TR] Eger varsa hosts dosyasindaki kurulum bloklarini temizle
REM ==============================================================================
if exist "%WINDIR%\System32\drivers\etc\hosts" (
    findstr /v /c:"NTLNDUP" "%WINDIR%\System32\drivers\etc\hosts" > "%WINDIR%\System32\drivers\etc\hosts.ntl" 2>nul
    if exist "%WINDIR%\System32\drivers\etc\hosts.ntl" (
        move /y "%WINDIR%\System32\drivers\etc\hosts.ntl" "%WINDIR%\System32\drivers\etc\hosts" >nul 2>&1
        del /q "%WINDIR%\System32\drivers\etc\hosts.ntl" >nul 2>&1
    )
)

REM ==============================================================================
REM [EN] Re-enable and start DHCP client service (restore network)
REM [TR] DHCP istemci servisini otomatik yap ve calistir (interneti geri ac)
REM ==============================================================================
reg add "HKLM\SYSTEM\CurrentControlSet\Services\Dhcp" /v Start /t REG_DWORD /d 2 /f >nul 2>&1
reg add "HKLM\SYSTEM\ControlSet001\Services\Dhcp" /v Start /t REG_DWORD /d 2 /f >nul 2>&1
sc.exe config "Dhcp" start= auto >nul 2>&1
sc.exe start "Dhcp" >nul 2>&1

REM ==============================================================================
REM [EN] Restore IPv6 configuration
REM [TR] IPv6 bilesen engelini kaldir
REM ==============================================================================
reg delete "HKLM\SYSTEM\CurrentControlSet\Services\Tcpip6\Parameters" /v DisabledComponents /f >nul 2>&1
reg delete "HKLM\SYSTEM\ControlSet001\Services\Tcpip6\Parameters" /v DisabledComponents /f >nul 2>&1

REM ==============================================================================
REM [EN] Enable NCSI (Network Connectivity Status Indicator) probing
REM [TR] NCSI internet algilama probunu hem CurrentControlSet hem ControlSet001'de ac
REM ==============================================================================
reg add "HKLM\SYSTEM\CurrentControlSet\Services\NlaSvc\Parameters\Internet" /v EnableActiveProbing /t REG_DWORD /d 1 /f >nul 2>&1
reg add "HKLM\SYSTEM\ControlSet001\Services\NlaSvc\Parameters\Internet" /v EnableActiveProbing /t REG_DWORD /d 1 /f >nul 2>&1

REM ==============================================================================
REM [EN] Trigger background NCSI probe without locking NlaSvc
REM [TR] NlaSvc servisini kilitlemeden arka planda aktif NCSI probunu tetikle
REM ==============================================================================
start /b "" powershell -NoProfile -Command "try { (New-Object Net.WebClient).DownloadString('http://www.msftconnecttest.com/connecttest.txt') } catch {}" >nul 2>&1

REM ==============================================================================
REM [EN] Renew IP and network configuration
REM [TR] IP ve ag yapilandirmasini yenile
REM ==============================================================================
ipconfig /renew >nul 2>&1

REM ==============================================================================
REM [EN] Wait for active internet connection (ping loop safe for Session 0)
REM [TR] Internet baglantisini bekle (Session 0'da cokmeyi onlemek icin ping dongusu)
REM ==============================================================================
set /a TRYCOUNT=0
:WAITNET
ping -n 1 8.8.8.8 >nul 2>&1
if errorlevel 1 (
    set /a TRYCOUNT=!TRYCOUNT!+1
    if !TRYCOUNT! GTR 15 (
        goto SKIPNET
    )
    ping 127.0.0.1 -n 3 >nul
    goto WAITNET
)

REM ==============================================================================
REM [EN] Internet connected: ensure NCSI state stabilization via HTTP probe
REM [TR] Internet baglandi: HTTP probu ile NCSI durumunu sabitle ve bekle
REM ==============================================================================
start /b "" powershell -NoProfile -Command "try { (New-Object Net.WebClient).DownloadString('http://www.msftconnecttest.com/connecttest.txt') } catch {}" >nul 2>&1
ping 127.0.0.1 -n 6 >nul

:SKIPNET
REM ==============================================================================
REM [EN] Detect installation media and read activation flag from ei.cfg
REM [TR] Kurulum medyasini tara ve ei.cfg icindeki aktivasyon bayragini oku
REM ==============================================================================
set SETUPDISK=0
FOR %%a IN (D E F G H I J K L M N O P Q R S T U V W X Y Z) DO IF EXIST %%a:\sources\ei.cfg (FOR /F "delims== tokens=2* usebackq" %%b in (`type "%%a:\sources\ei.cfg" ^| findstr /i "Aktivasyon= Activation="`) do (
    set SETUPDISK=%%a
    set ACTIVATION_STATUS=%%b
    )
)

set "MAS_DOWNLOADED=0"
set "MAS_TEMP=%~dp0MAS_AIO_new.cmd"
set "MAS_TARGET=%~dp0MAS_AIO.cmd"
set "MAS_DESKTOP=C:\Users\Public\Desktop\%ACT_FOLDER%\MAS_AIO.cmd"

REM ==============================================================================
REM [EN] Attempt to download latest MAS_AIO.cmd from mirrors
REM [TR] Yansilardan en guncel MAS_AIO.cmd dosyasini indirmeyi dene
REM ==============================================================================

REM [EN] Source 1: GitHub Raw / [TR] Kaynak 1: GitHub Raw
powershell -NoProfile -ExecutionPolicy Bypass -Command "[Net.ServicePointManager]::SecurityProtocol=[Net.SecurityProtocolType]::Tls12; try { Invoke-WebRequest -Uri 'https://raw.githubusercontent.com/massgravel/Microsoft-Activation-Scripts/master/MAS/All-In-One-Version-KL/MAS_AIO.cmd' -OutFile '%MAS_TEMP%' -UseBasicParsing -TimeoutSec 15 -ErrorAction Stop } catch { exit 1 }"
if not errorlevel 1 if exist "%MAS_TEMP%" (
   for %%s in ("%MAS_TEMP%") do if %%~zs GTR 1000 set "MAS_DOWNLOADED=1"
)

REM [EN] Source 2: Azure DevOps / [TR] Kaynak 2: Azure DevOps
if "!MAS_DOWNLOADED!" == "0" (
   if exist "%MAS_TEMP%" del /f /q "%MAS_TEMP%" >nul 2>&1
   powershell -NoProfile -ExecutionPolicy Bypass -Command "[Net.ServicePointManager]::SecurityProtocol=[Net.SecurityProtocolType]::Tls12; try { Invoke-WebRequest -Uri 'https://dev.azure.com/massgrave/Microsoft-Activation-Scripts/_apis/git/repositories/Microsoft-Activation-Scripts/items?path=/MAS/All-In-One-Version-KL/MAS_AIO.cmd&download=true' -OutFile '%MAS_TEMP%' -UseBasicParsing -TimeoutSec 15 -ErrorAction Stop } catch { exit 1 }"
   if not errorlevel 1 if exist "%MAS_TEMP%" (
      for %%s in ("%MAS_TEMP%") do if %%~zs GTR 1000 set "MAS_DOWNLOADED=1"
   )
)

REM [EN] Source 3: Self-hosted Git / [TR] Kaynak 3: Self-hosted Git
if "!MAS_DOWNLOADED!" == "0" (
   if exist "%MAS_TEMP%" del /f /q "%MAS_TEMP%" >nul 2>&1
   powershell -NoProfile -ExecutionPolicy Bypass -Command "[Net.ServicePointManager]::SecurityProtocol=[Net.SecurityProtocolType]::Tls12; try { Invoke-WebRequest -Uri 'https://git.activated.win/massgrave/Microsoft-Activation-Scripts/raw/branch/master/MAS/All-In-One-Version-KL/MAS_AIO.cmd' -OutFile '%MAS_TEMP%' -UseBasicParsing -TimeoutSec 15 -ErrorAction Stop } catch { exit 1 }"
   if not errorlevel 1 if exist "%MAS_TEMP%" (
      for %%s in ("%MAS_TEMP%") do if %%~zs GTR 1000 set "MAS_DOWNLOADED=1"
   )
)

REM ==============================================================================
REM [EN] Copy downloaded file to target directories if download succeeded
REM [TR] Indirme basariliysa dosyayi hedef konumlara kopyala
REM ==============================================================================
if "!MAS_DOWNLOADED!" == "1" (
   if not exist "C:\Users\Public\Desktop\%ACT_FOLDER%" mkdir "C:\Users\Public\Desktop\%ACT_FOLDER%" >nul 2>&1
   copy /y "%MAS_TEMP%" "%MAS_TARGET%" >nul 2>&1
   copy /y "%MAS_TEMP%" "%MAS_DESKTOP%" >nul 2>&1
   del /f /q "%MAS_TEMP%" >nul 2>&1
) else (
   REM [EN] Fallback: If media has bundled MAS_AIO, copy to desktop
   REM [TR] Yedek plan: Eger medyada hazir MAS_AIO varsa masaustune kopyala
   if exist "%MAS_TARGET%" (
      if not exist "C:\Users\Public\Desktop\%ACT_FOLDER%" mkdir "C:\Users\Public\Desktop\%ACT_FOLDER%" >nul 2>&1
      copy /y "%MAS_TARGET%" "%MAS_DESKTOP%" >nul 2>&1
   )
)

REM ==============================================================================
REM [EN] Run HWID activation if activation flag is 1
REM [TR] Aktivasyon bayragi 1 ise HWID aktivasyonunu calistir
REM ==============================================================================
If %ACTIVATION_STATUS% == 1 (
   if exist "%MAS_TARGET%" (
      call "%MAS_TARGET%" /HWID
   )
)

REM ==============================================================================
REM [EN] Queue post-install software and tweaks via RunOnceEx
REM [TR] Kurulum sonrasi yazilim ve ince ayarlari RunOnceEx ile siraya ekle
REM ==============================================================================
set /a KEYNUM=1
SET KEY=HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnceEx
REG ADD %KEY% /V TITLE /D "%TXT_TITLE%" /f

REM [EN] Scan external drives for software installers / [TR] Harici suruculerde yazilim yukleyicilerini tara
FOR %%i IN (D E F G H I J K L M N O P Q R S T U V W X Y Z) DO IF EXIST %%i:\software (for /f "delims=" %%z in ('dir /b %%i:\software\*.exe') do (
call :RunOnceEx
REG ADD %KEY%\Burak!KEYNUM! /VE /D "%%~nz" /f >nul 2>&1
REG ADD %KEY%\Burak!KEYNUM! /V 1 /D "%%i:\software\%%z" /f >nul 2>&1
))

REM [EN] Scan external drives for system tweaks / [TR] Harici Suruculerde Sistem Ayarlarini Tara
FOR %%i IN (D E F G H I J K L M N O P Q R S T U V W X Y Z) DO IF EXIST %%i:\tweaks (for /f "delims=" %%z in ('dir /b %%i:\tweaks\*.reg %%i:\tweaks\*.cmd %%i:\tweaks\*.bat %%i:\tweaks\*.vbs %%i:\tweaks\*.vbe') do (
	call :RunOnceEx
	REG ADD %KEY%\Burak!KEYNUM! /VE /D "%%~nz" /f >nul 2>&1
	If "%%~xz" == ".reg" (
		REG ADD %KEY%\Burak!KEYNUM! /V 1 /D "regedit.exe /s \"%%i:\tweaks\%%z\"" /f >nul 2>&1
	) else if "%%~xz" == ".vbs" (
        REG ADD %KEY%\Burak!KEYNUM! /V 1 /D "cscript.exe //B \"%%i:\tweaks\%%z\"" /f >nul 2>&1
    ) else if "%%~xz" == ".vbe" (
        REG ADD %KEY%\Burak!KEYNUM! /V 1 /D "cscript.exe //B \"%%i:\tweaks\%%z\"" /f >nul 2>&1
    ) else (
        REG ADD %KEY%\Burak!KEYNUM! /V 1 /D "cmd /c \"%%i:\tweaks\%%z\"" /f >nul 2>&1
    )
	))

REM [EN] Clean up setup scripts directory / [TR] Kurulum Script Klasorunu Temizle
RMDIR /S /Q "%~dp0" >nul 2>&1
exit

:RunOnceEx
set /a KEYNUM=!KEYNUM!+1
