@echo off
setlocal EnableExtensions EnableDelayedExpansion
chcp 65001 >nul 2>&1
title DeadMoon LunarCraft // Portable One-Click Installer
color 0B

set "INSTALL_DIR=%USERPROFILE%\Desktop\DeadMoon-LunarCraft"
set "PRISM_DIR=%INSTALL_DIR%\PrismLauncher"
set "MRPACK_NAME=deadmoon.mrpack"
set "MRPACK_PATH=%INSTALL_DIR%\%MRPACK_NAME%"
set "ICON_NAME=deadmoon.png"
set "PRISM_ICONS_DIR=%PRISM_DIR%\icons"
set "INSTANCE_NAME=DeadMoon Modpack"
set "PRIMARY_MRPACK_URL=https://download.deadfriends.party/downloads/deadmoon.mrpack"
set "FALLBACK_MRPACK_URL=https://code.deadmoon.ca/Deadplayerdmr/DeadMoon-LunarCraft/raw/branch/main/assets/deadmoon.mrpack"
set "PRIMARY_ICON_URL=https://download.deadfriends.party/static/branding/deadmoon.png"
set "FALLBACK_ICON_URL=https://download.deadfriends.party/downloads/deadmoon.png"
set "PRISM_FALLBACK_URL=https://github.com/Diegiwg/PrismLauncher-Cracked/releases/download/v12.0.0/PrismLauncher-Windows-MinGW-w64-Portable-12.0.0.zip"

cls
echo.
echo   =========================================================================
echo        .   *        .       .       *        .      .       *       .
echo           ___  ____ ____ ___  _  _ ____ ____ _  _
echo           ^|  \ ^|___ ^|__^| ^|  \ ^|\/ ^| ^|  ^| ^|  ^| ^|\ ^|   //  L U N A R C R A F T
echo           ^|__/ ^|___ ^|  ^| ^|__/ ^|  ^| ^|__^| ^|__^| ^| \^|   Paper 26.3 Survival
echo        *     (   D E A D M O O N  //  L U N A R C R A F T   )     *
echo   =========================================================================
echo     Portable Zero-Clutter Setup  ^|  Server: play.deadfriends.party
echo   =========================================================================
echo.

:ASK_USER
set "MC_USER="
set /p "MC_USER=  [1/5] Enter your offline Minecraft username (3-16 chars, A-Z 0-9 _): "
if not defined MC_USER goto :BAD_USER
powershell -NoProfile -ExecutionPolicy Bypass -Command "if ('!MC_USER!' -match '^[A-Za-z0-9_]{3,16}$') { exit 0 } else { exit 1 }"
if errorlevel 1 goto :BAD_USER
goto :USER_OK

:BAD_USER
echo   [!] Invalid username. Use 3 to 16 letters, numbers, or underscores only.
goto :ASK_USER

:USER_OK
echo   [OK] Welcome to the Moon, !MC_USER!!
echo.
echo   [2/5] Preparing portable folder: %INSTALL_DIR%
if not exist "%INSTALL_DIR%" mkdir "%INSTALL_DIR%"
if not exist "%PRISM_DIR%" mkdir "%PRISM_DIR%"

echo   [3/5] Downloading Portable PrismLauncher-Cracked (Diegiwg)...
powershell -NoProfile -ExecutionPolicy Bypass -Command ^
  "$ErrorActionPreference = 'Stop'; ^
   [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; ^
   $zipPath = Join-Path '%INSTALL_DIR%' 'prism-portable.zip'; ^
   $prismDir = '%PRISM_DIR%'; ^
   if (Test-Path (Join-Path $prismDir 'prismlauncher.exe')) { Write-Host '  [OK] PrismLauncher already installed.'; exit 0 }; ^
   $dlUrl = '%PRISM_FALLBACK_URL%'; ^
   try { ^
     $rel = Invoke-RestMethod -Uri 'https://api.github.com/repos/Diegiwg/PrismLauncher-Cracked/releases/latest' -Headers @{ 'User-Agent' = 'DeadMoon-LunarCraft-Installer' } -TimeoutSec 20; ^
     $asset = $rel.assets | Where-Object { $_.name -like 'PrismLauncher-Windows-MinGW-w64-*.zip' } | Select-Object -First 1; ^
     if (-not $asset) { $asset = $rel.assets | Where-Object { $_.name -like 'PrismLauncher-Windows-*.zip' -and $_.name -like '*Portable*' } | Select-Object -First 1 }; ^
     if ($asset -and $asset.browser_download_url) { $dlUrl = $asset.browser_download_url }; ^
   } catch { Write-Host '  [!] GitHub API unreachable, falling back to v12.0.0 direct release.' }; ^
   Write-Host ('  -> Fetching: ' + $dlUrl); ^
   Invoke-WebRequest -Uri $dlUrl -OutFile $zipPath -UseBasicParsing; ^
   Expand-Archive -Path $zipPath -DestinationPath $prismDir -Force; ^
   Remove-Item $zipPath -Force -ErrorAction SilentlyContinue; ^
   if (-not (Test-Path (Join-Path $prismDir 'prismlauncher.exe'))) { ^
     $nested = Get-ChildItem -Path $prismDir -Recurse -Filter 'prismlauncher.exe' | Select-Object -First 1; ^
     if ($nested) { ^
       Get-ChildItem -Path $nested.DirectoryName | Move-Item -Destination $prismDir -Force; ^
     } ^
   }; ^
   Set-Content -Path (Join-Path $prismDir 'portable.txt') -Value 'DeadMoon-LunarCraft Portable Mode' -Encoding ASCII; ^
   Write-Host '  [OK] Portable PrismLauncher ready.'"
if errorlevel 1 (
  echo.
  echo   [ERROR] Could not download PrismLauncher-Cracked. Check your internet connection and retry.
  pause
  exit /b 1
)

echo.
echo   [4/5] Downloading DeadMoon Modpack (deadmoon.mrpack) ^& LunarCraft Icon (deadmoon.png)...
powershell -NoProfile -ExecutionPolicy Bypass -Command ^
  "$ErrorActionPreference = 'Stop'; ^
   [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; ^
   $dst = '%MRPACK_PATH%'; ^
   $urls = @('%PRIMARY_MRPACK_URL%', '%FALLBACK_MRPACK_URL%'); ^
   $ok = $false; ^
   foreach ($u in $urls) { ^
     try { ^
       Write-Host ('  -> Trying: ' + $u); ^
       Invoke-WebRequest -Uri $u -OutFile $dst -UseBasicParsing -TimeoutSec 60; ^
       if ((Test-Path $dst) -and ((Get-Item $dst).Length -gt 256)) { $ok = $true; break }; ^
     } catch { Write-Host ('  [!] Mirror failed: ' + $u) } ^
   }; ^
   if (-not $ok) { throw 'All deadmoon.mrpack download mirrors failed. Grab it from https://download.deadfriends.party' }; ^
   Write-Host ('  [OK] Downloaded ' + $dst); ^
   $iconsDir = '%PRISM_ICONS_DIR%'; ^
   New-Item -ItemType Directory -Force -Path $iconsDir | Out-Null; ^
   $iconDst = Join-Path $iconsDir '%ICON_NAME%'; ^
   $iconUrls = @('%PRIMARY_ICON_URL%', '%FALLBACK_ICON_URL%'); ^
   foreach ($iu in $iconUrls) { ^
     try { ^
       Invoke-WebRequest -Uri $iu -OutFile $iconDst -UseBasicParsing -TimeoutSec 30; ^
       if ((Test-Path $iconDst) -and ((Get-Item $iconDst).Length -gt 128)) { ^
         Write-Host ('  [OK] Installed LunarCraft icon -> ' + $iconDst); ^
         break; ^
       } ^
     } catch { Write-Host ('  [!] Icon mirror skipped: ' + $iu) } ^
   }; ^
   $instDir = Join-Path '%PRISM_DIR%' 'instances'; ^
   New-Item -ItemType Directory -Force -Path $instDir | Out-Null; ^
   $cfgDirs = Get-ChildItem -Path $instDir -Directory -ErrorAction SilentlyContinue | Where-Object { $_.Name -like '*DeadMoon*' }; ^
   foreach ($d in $cfgDirs) { ^
     $cfgPath = Join-Path $d.FullName 'instance.cfg'; ^
     if (Test-Path $cfgPath) { ^
       $txt = Get-Content $cfgPath -Raw; ^
       if ($txt -match '(?m)^iconKey=') { $txt = $txt -replace '(?m)^iconKey=.*', 'iconKey=deadmoon' } else { $txt = $txt.TrimEnd() + \"`r`niconKey=deadmoon`r`n\" }; ^
       if ($txt -match '(?m)^name=') { $txt = $txt -replace '(?m)^name=.*', 'name=DeadMoon Modpack' } else { $txt = $txt.TrimEnd() + \"`r`nname=DeadMoon Modpack`r`n\" }; ^
       Set-Content -Path $cfgPath -Value $txt -Encoding UTF8; ^
     } ^
   }"
if errorlevel 1 (
  echo.
  echo   [ERROR] Could not download deadmoon.mrpack.
  echo   You can manually download it from https://download.deadfriends.party
  pause
  exit /b 1
)

echo.
echo   =========================================================================
echo     [5/5] LAUNCHING PRISM LAUNCHER TO IMPORT DEADMOON MODPACK!
echo   =========================================================================
echo     1. In PrismLauncher, add Offline Account:  !MC_USER!
echo     2. Click OK on the Modpack Import dialog ("DeadMoon Modpack")
echo     3. Launch instance ^& connect to:  play.deadfriends.party
echo     4. First join: type  /register ^<password^> ^<password^>
echo     5. Menus:      press ESC -^> DeadMoon Menu  ^|  /skins  ^|  /radio  ^|  /hud
echo     6. Shaders:    press [I] in-game for Shaders (Gaming PCs) or leave OFF (Laptops)
echo   =========================================================================
echo.
start "DeadMoon Modpack" "%PRISM_DIR%\prismlauncher.exe" --dir "%PRISM_DIR%" --import "%MRPACK_PATH%"

REM Background helper: once Prism finishes creating the DeadMoon Modpack instance.cfg, set iconKey=deadmoon automatically
powershell -NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -Command ^
  "$instRoot = Join-Path '%PRISM_DIR%' 'instances'; ^
   for ($i = 0; $i -lt 90; $i++) { ^
     Start-Sleep -Seconds 2; ^
     if (Test-Path $instRoot) { ^
       $match = Get-ChildItem -Path $instRoot -Directory -ErrorAction SilentlyContinue | Where-Object { $_.Name -like '*DeadMoon*' } | Select-Object -First 1; ^
       if ($match) { ^
         $cfgPath = Join-Path $match.FullName 'instance.cfg'; ^
         if (Test-Path $cfgPath) { ^
           $txt = Get-Content $cfgPath -Raw; ^
           if ($txt -match '(?m)^iconKey=') { $txt = $txt -replace '(?m)^iconKey=.*', 'iconKey=deadmoon' } else { $txt = $txt.TrimEnd() + \"`r`niconKey=deadmoon`r`n\" }; ^
           if ($txt -match '(?m)^name=') { $txt = $txt -replace '(?m)^name=.*', 'name=DeadMoon Modpack' } else { $txt = $txt.TrimEnd() + \"`r`nname=DeadMoon Modpack`r`n\" }; ^
           Set-Content -Path $cfgPath -Value $txt -Encoding UTF8; ^
           break; ^
         } ^
       } ^
     } ^
   }"
echo   Installer finished! You can find everything inside: %INSTALL_DIR%
pause
endlocal
exit /b 0
