#!/usr/bin/env bash
# Despliega el backend Suyu al hosting compartido cPanel.
# Se corre DESDE la máquina de desarrollo (WSL), donde vive el repo.
# Requiere: deploy/deploy.config (copiado y completado desde
# deploy.config.example) y, en el primer despliegue, deploy/.env.production
# (copiado y completado desde .env.production.example).
set -euo pipefail

cd "$(dirname "$0")/.."
ROOT="$(pwd)"

if [ ! -f deploy/deploy.config ]; then
  echo "Falta deploy/deploy.config — copia deploy/deploy.config.example y completa tus datos." >&2
  exit 1
fi
source deploy/deploy.config

SSH_TARGET="${SSH_USER}@${SSH_HOST}"
SSH_OPTS=(-p "${SSH_PORT}")
RSYNC_SSH="ssh -p ${SSH_PORT}"

echo "==> Corriendo la suite de tests local antes de desplegar"
docker exec -u sail inmo-backend-laravel.test-1 bash -c "cd /var/www/html && php artisan test" || {
  echo "Los tests fallaron — no se despliega. Revisa antes de reintentar." >&2
  exit 1
}

echo "==> Compilando assets del portal web (Vite/Inertia) — el hosting no tiene Node"
docker exec -u sail inmo-backend-laravel.test-1 bash -c "cd /var/www/html && npm run build"

echo "==> Subiendo archivos por rsync a ${SSH_TARGET}:${REMOTE_APP_PATH}"
ssh "${SSH_OPTS[@]}" "${SSH_TARGET}" "mkdir -p '${REMOTE_APP_PATH}'"
rsync -avz --delete \
  -e "${RSYNC_SSH}" \
  --exclude '.git' \
  --exclude 'node_modules' \
  --exclude '.env' \
  --exclude 'storage/logs/*' \
  --exclude 'storage/framework/cache/*' \
  --exclude 'storage/framework/sessions/*' \
  --exclude 'storage/framework/views/*' \
  --exclude 'storage/framework/testing/*' \
  --exclude 'deploy/deploy.config' \
  --exclude 'deploy/.env.production' \
  --exclude 'tests' \
  "${ROOT}/" "${SSH_TARGET}:${REMOTE_APP_PATH}/"

REMOTE_ENV_EXISTS=$(ssh "${SSH_OPTS[@]}" "${SSH_TARGET}" "[ -f '${REMOTE_APP_PATH}/.env' ] && echo yes || echo no")
if [ "${REMOTE_ENV_EXISTS}" = "no" ]; then
  if [ ! -f deploy/.env.production ]; then
    echo "El servidor no tiene .env todavía y falta deploy/.env.production — copia deploy/.env.production.example y completa." >&2
    exit 1
  fi
  echo "==> Primer despliegue: subiendo deploy/.env.production como .env del servidor"
  scp -P "${SSH_PORT}" deploy/.env.production "${SSH_TARGET}:${REMOTE_APP_PATH}/.env"
else
  echo "==> El servidor ya tiene .env — no se pisa (edítalo a mano por SSH si necesitas cambiar algo)"
fi

echo "==> Corriendo composer/artisan en el servidor"
ssh "${SSH_OPTS[@]}" "${SSH_TARGET}" bash -s <<REMOTE
set -euo pipefail
cd "${REMOTE_APP_PATH}"

composer install --no-dev --optimize-autoloader --no-interaction

if ! grep -q '^APP_KEY=base64' .env; then
  php artisan key:generate --force
fi

php artisan migrate --force

# storage:link puede fallar si el hosting bloquea symlink() por open_basedir;
# si falla, hay que copiar storage/app/public a public/storage a mano.
php artisan storage:link || echo "AVISO: storage:link falló — revisa deploy/CPANEL_SETUP.md (fallback sin symlink)."

php artisan config:cache
php artisan route:cache
php artisan view:cache

chmod -R 775 storage bootstrap/cache
REMOTE

echo "==> Listo. Verifica https://suyu.datasol.org/ y sigue deploy/CPANEL_SETUP.md si es el primer despliegue (subdominio, cron, SSL)."
