@echo off
setlocal EnableExtensions EnableDelayedExpansion

REM ============================================================================
REM  Flexia / Antara — respaldo para reinstalacion
REM  Copia el codigo y recursos del proyecto SIN medias ni configuraciones de
REM  usuario/instancia. El resultado sirve para desplegar como 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_install_source_%STAMP%"

echo.
echo  Flexia — respaldo instalable (sin datos de usuario)
echo  ====================================================
echo  Origen : %PROJECT_ROOT%
echo  Destino: %DEST%
echo.

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

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

echo Copiando archivos (robocopy)...
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%\arquitect-app\reserved_projects" ^
       "%PROJECT_ROOT%\..\backups" ^
    /XF "settings.json" "settings.json.bak" ".user.ini" "explorer_customization.json" ^
       ".share_secret.key" "install.lock" "auth_config.enc" "users.enc" "webauthn_credentials.enc" "rate.enc" ^
       "flexia_instance.json" "flexia_format_count.json" "flexia_traffic_stats.json" "activity.log" "security.log" ^
    /XF "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 Creando estructura vacia para una instalacion nueva...

for %%D in (
    "%DEST%\config"
    "%DEST%\media\explorer\files"
    "%DEST%\media\explorer\trash"
    "%DEST%\media\explorer\users"
    "%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"

(
    echo Flexia — respaldo instalable
    echo Generado: %STAMP%
    echo.
    echo EXCLUIDO del respaldo:
    echo   - storage\users\          perfiles y settings personales
    echo   - storage\secure\         usuarios/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 en la instalacion
    echo   - settings.json           configuracion del workspace
    echo   - config\explorer_customization.json
    echo   - logs\, temp\, proyectos en arquitect-app\reserved_projects\
    echo.
    echo Para instalar: sube esta carpeta al hosting y abre /install/
) > "%DEST%\RESPALDO_INSTALABLE.txt"

echo.
echo Comprimiendo ZIP...
set "ZIP=%BACKUPS_PARENT%\flexia_install_source_%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 copia en carpeta si esta lista.
    set "ZIP="
) else (
    echo ZIP creado: %ZIP%
)

echo.
echo ====================================================
echo  Respaldo completado.
echo  Carpeta: %DEST%
if defined ZIP echo  ZIP    : %ZIP%
echo ====================================================
echo.
pause
exit /b 0
