@echo off
setlocal enabledelayedexpansion
title Forja de Oldenait - instalar build

rem ===================================================================
rem  Forja de Oldenait - https://www.oldenait.com
rem
rem  Que hace, en orden:
rem    1. busca donde esta instalado League of Legends
rem    2. lee el lockfile, que el cliente deja mientras corre y que
rem       trae el puerto y la clave de su API local
rem    3. baja esta build de oldenait.com
rem    4. se la agrega a tus paginas de objetos por esa API local
rem
rem  No instala nada, no toca el registro, no queda corriendo y no le
rem  manda nada a nadie: solo le habla a tu propio cliente, que corre
rem  en 127.0.0.1. La clave del lockfile la genera el cliente cuando
rem  arranca y muere cuando lo cerras.
rem ===================================================================

set "CAMPEON=Pyke"
set "URL=https://oldenait.com/herramientas/forja/api.php?a=itemset&c=Pyke&rol=UTILITY"
set "TRABAJO=%TEMP%\forja-oldenait"

echo.
echo   ================================================
echo    FORJA DE OLDENAIT
echo   ================================================
echo.
echo    Build   : Pyke Support . meta
echo    Campeon : %CAMPEON%
echo.

rem --- 0. curl tiene que existir -------------------------------------
where curl.exe >nul 2>nul
if errorlevel 1 (
  echo    [ERROR] No encontre curl.exe.
  echo    Viene con Windows 10 desde 2018. Si tenes uno mas viejo,
  echo    la build hay que armarla a mano en el cliente.
  echo.
  pause
  exit /b 1
)

rem --- 1. Buscar la instalacion --------------------------------------
set "LOL="

for /f "tokens=2,*" %%A in ('reg query "HKLM\SOFTWARE\WOW6432Node\Riot Games, Inc\League of Legends" /v Location 2^>nul ^| findstr /i "Location"') do set "LOL=%%B"
if defined LOL if not exist "!LOL!\LeagueClient.exe" set "LOL="

if not defined LOL for %%D in (C D E F) do (
  if not defined LOL if exist "%%D:\Riot Games\League of Legends\LeagueClient.exe" set "LOL=%%D:\Riot Games\League of Legends"
)
if not defined LOL if exist "%ProgramFiles%\Riot Games\League of Legends\LeagueClient.exe" set "LOL=%ProgramFiles%\Riot Games\League of Legends"
if not defined LOL if exist "%ProgramFiles(x86)%\Riot Games\League of Legends\LeagueClient.exe" set "LOL=%ProgramFiles(x86)%\Riot Games\League of Legends"

if not defined LOL (
  echo    No encontre la instalacion de League of Legends.
  echo    Arrastra aca la carpeta "League of Legends" y apreta Enter,
  echo    o pega la ruta a mano.
  echo.
  set /p "RUTA=   Carpeta: "
)

rem Al arrastrar una carpeta, cmd la pega entre comillas: hay que sacarlas.
rem Esta linea va suelta a proposito: una comilla impar adentro de un
rem bloque entre parentesis le rompe el parseo a cmd.
if defined RUTA set RUTA=!RUTA:"=!
if defined RUTA set "LOL=!RUTA!"

if not exist "!LOL!\LeagueClient.exe" (
  echo.
  echo    [ERROR] En esa carpeta no esta LeagueClient.exe.
  echo    Tiene que ser la carpeta "League of Legends", la que tiene
  echo    adentro LeagueClient.exe y la carpeta Config.
  echo.
  pause
  exit /b 1
)

rem --- 2. El cliente tiene que estar abierto -------------------------
if not exist "!LOL!\lockfile" (
  echo.
  echo    [ERROR] El cliente de League of Legends esta cerrado.
  echo.
  echo    Abrilo, espera a que cargue del todo y volve a ejecutar este
  echo    archivo. La build se agrega al instante, sin reiniciar nada.
  echo.
  pause
  exit /b 1
)

if not exist "!TRABAJO!" mkdir "!TRABAJO!" 2>nul
set "LOLDIR=!LOL!"
set "FORJATMP=!TRABAJO!"

rem --- 3. Credenciales de la API local -------------------------------
rem PowerShell lee el lockfile y deja las credenciales en un archivo de
rem configuracion de curl, para que la clave no viaje en la linea de
rem comandos, que cualquier proceso de la maquina puede leer.
rem El lockfile es  nombre:pid:puerto:clave:protocolo

set "PS="
set "PS=!PS! $ErrorActionPreference = 'Stop';"
set "PS=!PS! $p = (Get-Content -Raw -LiteralPath ($env:LOLDIR + '\lockfile')).Trim().Split(':');"
set "PS=!PS! $q = [char]34;"
set "PS=!PS! $cfg = 'user = ' + $q + 'riot:' + $p[3] + $q + [Environment]::NewLine + 'insecure' + [Environment]::NewLine + 'silent' + [Environment]::NewLine + 'show-error';"
set "PS=!PS! [IO.File]::WriteAllText($env:FORJATMP + '\curl.cfg', $cfg, (New-Object Text.UTF8Encoding $false));"
set "PS=!PS! [IO.File]::WriteAllText($env:FORJATMP + '\puerto.txt', $p[2], (New-Object Text.UTF8Encoding $false));"
powershell -NoProfile -ExecutionPolicy Bypass -Command "!PS!"
if errorlevel 1 goto :falla

set "PUERTO="
for /f "usebackq delims=" %%A in ("!TRABAJO!\puerto.txt") do set "PUERTO=%%A"
if not defined PUERTO goto :falla

set "CFG=!TRABAJO!\curl.cfg"
set "BASE=https://127.0.0.1:!PUERTO!"

rem --- 4. Quien sos y que paginas tenes ------------------------------
echo    Hablandole al cliente...
curl -K "!CFG!" -f -o "!TRABAJO!\yo.json" "!BASE!/lol-summoner/v1/current-summoner"
if errorlevel 1 goto :falla

set "PS="
set "PS=!PS! $ErrorActionPreference = 'Stop';"
set "PS=!PS! $yo = Get-Content -Raw -LiteralPath ($env:FORJATMP + '\yo.json') | ConvertFrom-Json;"
set "PS=!PS! [IO.File]::WriteAllText($env:FORJATMP + '\sid.txt', [string]$yo.summonerId, (New-Object Text.UTF8Encoding $false));"
powershell -NoProfile -ExecutionPolicy Bypass -Command "!PS!"
if errorlevel 1 goto :falla

set "SID="
for /f "usebackq delims=" %%A in ("!TRABAJO!\sid.txt") do set "SID=%%A"
if not defined SID goto :falla

set "PUNTO=!BASE!/lol-item-sets/v1/item-sets/!SID!/sets"
curl -K "!CFG!" -f -o "!TRABAJO!\actuales.json" "!PUNTO!"
if errorlevel 1 goto :falla

rem --- 5. Bajar la build --------------------------------------------
echo    Bajando la build...
curl -f -s -S -L -o "!TRABAJO!\build.json" "%URL%"
if errorlevel 1 (
  echo.
  echo    [ERROR] No se pudo bajar la build de oldenait.com.
  echo    Revisa la conexion a internet.
  echo.
  goto :limpiar_y_salir
)

rem --- 6. Mezclar y devolver la lista completa -----------------------
rem El endpoint reemplaza TODA la lista, asi que hay que mandarla
rem entera. Se saca primero cualquier pagina con el mismo uid, para que
rem instalar dos veces la misma build no deje dos copias.
rem WriteAllText con UTF8Encoding($false) es obligatorio: el BOM que
rem pone Set-Content hace que el cliente rechace el cuerpo entero.

set "PS="
set "PS=!PS! $ErrorActionPreference = 'Stop';"
set "PS=!PS! $act = Get-Content -Raw -LiteralPath ($env:FORJATMP + '\actuales.json') | ConvertFrom-Json;"
set "PS=!PS! $nueva = Get-Content -Raw -LiteralPath ($env:FORJATMP + '\build.json') | ConvertFrom-Json;"
set "PS=!PS! $resto = @($act.itemSets | Where-Object { $_.uid -ne $nueva.uid });"
set "PS=!PS! $act.itemSets = @($resto + $nueva);"
set "PS=!PS! $json = $act | ConvertTo-Json -Depth 20 -Compress;"
set "PS=!PS! [IO.File]::WriteAllText($env:FORJATMP + '\merge.json', $json, (New-Object Text.UTF8Encoding $false));"
set "PS=!PS! [IO.File]::WriteAllText($env:FORJATMP + '\total.txt', [string]$act.itemSets.Count, (New-Object Text.UTF8Encoding $false));"
powershell -NoProfile -ExecutionPolicy Bypass -Command "!PS!"
if errorlevel 1 goto :falla

curl -K "!CFG!" -f -X PUT -H "Content-Type: application/json" --data-binary "@!TRABAJO!\merge.json" -o nul "!PUNTO!"
if errorlevel 1 goto :falla

set "TOTAL=?"
for /f "usebackq delims=" %%A in ("!TRABAJO!\total.txt") do set "TOTAL=%%A"

call :limpiar
echo.
echo    LISTO. La build ya esta en tu cuenta.
echo    Te quedaron !TOTAL! paginas de objetos.
echo.
echo    Entra a una partida con %CAMPEON% y abri la tienda:
echo    aparece en la lista de paginas de objetos.
echo.
pause
exit /b 0

:falla
echo.
echo    [ERROR] No se pudo agregar la build.
echo.
echo    Las causas mas comunes, en orden:
echo      - el cliente todavia estaba cargando: espera y proba de nuevo
echo      - cerraste el cliente mientras corria esto
echo      - un antivirus bloqueo la conexion a 127.0.0.1
echo.

:limpiar_y_salir
call :limpiar
pause
exit /b 1

:limpiar
rem curl.cfg tiene la clave del cliente: no queda dando vueltas.
if exist "!TRABAJO!" rd /s /q "!TRABAJO!" 2>nul
goto :eof
