@echo off
setlocal EnableExtensions EnableDelayedExpansion

REM ============================================================================
REM  Flexia — respaldo en MODO INSTALADOR
REM
REM  Copia codigo y recursos estaticos del proyecto. NO incluye:
REM    - usuarios, credenciales, auth cifrado
REM    - settings del workspace ni perfiles personales
REM    - media, logos, documentos del explorador, flexia disk
REM    - install.lock ni estado de instancia
REM
REM  El resultado abre /install/ al desplegarlo (instalacion nueva).
REM ============================================================================

set "SCRIPT_DIR=%~dp0"
set "PROJECT_ROOT=%SCRIPT_DIR%.."
for %%I in ("%PROJECT_ROOT%") do set "PROJECT_ROOT=%%~fI"

for /f %%I in ('powershell -NoProfile -Command "Get-Date -Format yyyyMMdd_HHmmss"') do set "STAMP=%%I"

set "BACKUPS_PARENT=%PROJECT_ROOT%\..\backups"
set "DEST=%BACKUPS_PARENT%\flexia_modo_instalador_%STAMP%"

echo.
echo  Flexia — respaldo en modo instalador
echo  =====================================
echo  Origen : %PROJECT_ROOT%
echo  Destino: %DEST%
echo.

if not exist "%PROJECT_ROOT%\index.php" (
    echo [ERROR] No se encontro Flexia en:
    echo         %PROJECT_ROOT%
    exit /b 1
)

if not exist "%BACKUPS_PARENT%" mkdir "%BACKUPS_PARENT%"
if not exist "%DEST%" mkdir "%DEST%"

set "PHP_EXE="
where php >nul 2>&1 && set "PHP_EXE=php"
if not defined PHP_EXE if exist "D:\quadrata_app\php\php.exe" set "PHP_EXE=D:\quadrata_app\php\php.exe"
if not defined PHP_EXE if exist "%PROJECT_ROOT%\..\..\php\php.exe" (
    for %%I in ("%PROJECT_ROOT%\..\..\php\php.exe") do set "PHP_EXE=%%~fI"
)

echo [1/4] Copiando codigo sin datos de usuario ni instancia...
echo.

robocopy "%PROJECT_ROOT%" "%DEST%" /E /COPY:DAT /DCOPY:DAT /R:2 /W:2 /XJ ^
    /XD "%PROJECT_ROOT%\storage\users" ^
       "%PROJECT_ROOT%\storage\secure" ^
       "%PROJECT_ROOT%\storage\config" ^
       "%PROJECT_ROOT%\storage\logs" ^
       "%PROJECT_ROOT%\media" ^
       "%PROJECT_ROOT%\logos_sinapsys" ^
       "%PROJECT_ROOT%\logs" ^
       "%PROJECT_ROOT%\temp" ^
       "%PROJECT_ROOT%\config" ^
       "%PROJECT_ROOT%\share" ^
       "%PROJECT_ROOT%\flexia disk" ^
       "%PROJECT_ROOT%\arquitect-app\reserved_projects" ^
       "%PROJECT_ROOT%\..\backups" ^
       "%PROJECT_ROOT%\.git" ^
    /XF "settings.json" "settings.json.bak" ".user.ini" "explorer_customization.json" ^
       ".share_secret.key" "install.lock" "install_wizard_draft.json" ^
       "auth_config.enc" "users.enc" "webauthn_credentials.enc" "rate.enc" ^
       "flexia_instance.json" "flexia_format_count.json" "flexia_traffic_stats.json" ^
       "external_secrets_basename.txt" "recovery.allow" ^
       ".master.key" "master.key" "security.log" "activity.log" ^
       "users.json.bak*" ^
    /NFL /NDL /NP

set "RC=%ERRORLEVEL%"
if %RC% GEQ 8 (
    echo.
    echo [ERROR] Robocopy fallo con codigo %RC%.
    exit /b %RC%
)

echo.
echo [2/4] Creando estructura vacia de instalacion nueva...

for %%D in (
    "%DEST%\config"
    "%DEST%\media\explorer\files"
    "%DEST%\media\explorer\trash"
    "%DEST%\media\explorer\users"
    "%DEST%\media\explorer\departments"
    "%DEST%\media\explorer\remote-cache"
    "%DEST%\media\explorer\customization"
    "%DEST%\media\pwa"
    "%DEST%\logos_sinapsys"
    "%DEST%\logs"
    "%DEST%\temp"
    "%DEST%\share"
    "%DEST%\storage\users"
    "%DEST%\storage\secure"
    "%DEST%\storage\config"
    "%DEST%\storage\logs"
    "%DEST%\arquitect-app\reserved_projects"
) do if not exist "%%~D" mkdir "%%~D"

REM Copiar solo protecciones (.htaccess / index.php) de carpetas sensibles
for %%P in (
    "storage\.htaccess"
    "storage\index.php"
    "storage\users\.htaccess"
    "storage\users\index.php"
    "storage\secure\.htaccess"
    "storage\secure\index.php"
    "storage\config\.htaccess"
    "storage\config\index.php"
    "storage\logs\.htaccess"
    "storage\logs\index.php"
    "data\.htaccess"
    "logs\index.php"
    "logs\.htaccess"
) do (
    if exist "%PROJECT_ROOT%\%%~P" (
        for %%F in ("%%~P") do if not exist "%DEST%\%%~P" copy /Y "%PROJECT_ROOT%\%%~P" "%DEST%\%%~P" >nul
    )
)

echo.
echo [3/4] Sembrando settings por defecto y quitando install.lock...

if defined PHP_EXE (
    "%PHP_EXE%" "%SCRIPT_DIR%backup_installer_mode_seed.php" "%DEST%"
    if errorlevel 1 (
        echo [ERROR] No se pudo dejar el respaldo en modo instalador.
        exit /b 1
    )
) else (
    echo [AVISO] PHP no encontrado. Borrando install.lock manualmente...
    if exist "%DEST%\storage\config\install.lock" del /F /Q "%DEST%\storage\config\install.lock"
    echo [AVISO] Ejecuta manualmente:
    echo         php "%SCRIPT_DIR%backup_installer_mode_seed.php" "%DEST%"
)

if exist "%DEST%\storage\config\install.lock" (
    echo [ERROR] El respaldo aun contiene install.lock. Abortando.
    exit /b 1
)

echo.
echo [4/4] Comprimiendo ZIP...
set "ZIP=%BACKUPS_PARENT%\flexia_modo_instalador_%STAMP%.zip"
powershell -NoProfile -Command ^
    "if (Test-Path -LiteralPath '%ZIP%') { Remove-Item -LiteralPath '%ZIP%' -Force }; Compress-Archive -LiteralPath '%DEST%' -DestinationPath '%ZIP%' -CompressionLevel Optimal"

if errorlevel 1 (
    echo [AVISO] No se pudo crear el ZIP. La carpeta del respaldo si esta lista.
    set "ZIP="
) else (
    echo ZIP creado: %ZIP%
)

(
    echo Flexia — respaldo en modo instalador
    echo Generado: %STAMP%
    echo.
    echo Este paquete NO contiene datos de usuarios ni de la instancia anterior.
    echo Al subirlo a un hosting, abre /install/ y crea el primer superadmin.
    echo.
    echo EXCLUIDO del respaldo:
    echo   - storage\users\           perfiles y ajustes personales
    echo   - storage\secure\          usuarios y credenciales cifrados
    echo   - storage\config\          install.lock, instancia, auth, trafico
    echo   - storage\logs\            logs de seguridad
    echo   - media\                   archivos del explorador, PWA, caches
    echo   - logos_sinapsys\          logos subidos
    echo   - config\                  personalizacion del explorador
    echo   - flexia disk\             copias de recuperacion de documentos
    echo   - settings.json            configuracion del workspace
    echo   - arquitect-app\reserved_projects\
    echo.
    echo INCLUIDO: codigo fuente, assets estaticos, instalador /install/
) > "%DEST%\RESPALDO_MODO_INSTALADOR.txt"

echo.
echo =====================================
echo  Respaldo en modo instalador listo.
echo  Carpeta: %DEST%
if defined ZIP echo  ZIP    : %ZIP%
echo =====================================
echo.
pause
exit /b 0
