#!/usr/bin/env bash
set -euo pipefail
SRC="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
TARGET="${1:-/home/ai2go/ai2go_comercial}"
if [[ ! -d "$TARGET" || ! -f "$TARGET/app/bootstrap.php" || ! -d "$TARGET/public" ]]; then
  echo "ERROR: no parece una instalación existente Ai2GO en $TARGET" >&2; exit 1
fi
if [[ "$SRC" == "$TARGET" ]]; then echo 'ERROR: origen y destino son iguales.' >&2; exit 1; fi
if [[ ! -f "$TARGET/config/config.php" ]]; then
  echo 'ERROR: no existe config/config.php; configure ese archivo antes de actualizar.' >&2; exit 1
fi
if ! command -v php >/dev/null; then echo 'ERROR: no hay PHP CLI.' >&2; exit 1; fi
stamp="$(date +%Y%m%d_%H%M%S)"
BACKUP="$HOME/ai2go_respaldo_codigo_${stamp}.tar.gz"
umask 077
# Respalda el código y el config existente fuera del DocumentRoot. No incluye vendor ni datos DB.
tar -C "$TARGET" -czf "$BACKUP" app public config database tests composer.json
chmod 600 "$BACKUP"
echo "Respaldo: $BACKUP"
# Mantener intencionalmente config/config.php y DB, no tocar contraseñas ni registros.
for dir in app public database tests; do
  mkdir -p "$TARGET/$dir"
  cp -a "$SRC/$dir/." "$TARGET/$dir/"
done
cp -p "$SRC/.htaccess" "$TARGET/.htaccess"
cp -p "$SRC/composer.json" "$TARGET/composer.json"
cp -p "$SRC/config/config.example.php" "$TARGET/config/config.example.php"
cp -p "$SRC/config/CONFIG_PARA_COPIAR.php.txt" "$TARGET/config/CONFIG_PARA_COPIAR.php.txt"
chmod 600 "$TARGET/config/config.php"
echo 'NO se modificó config/config.php ni se alteró MySQL.'
cd "$TARGET"
php -l app/bootstrap.php
php -l public/index.php
php -l public/check-empresarial.php
php -l config/config.php
php tests/diagnostico_instalacion.php
echo 'CÓDIGO ACTUALIZADO PARA /public/. REVISA DOCUMENT ROOT EN CPANEL Y EDITA base_url EN config.php.'
