#!/usr/bin/env bash
set -euo pipefail

usage() {
  cat <<'TXT'
Uso:
  deploy-operaciones-app.sh <client_btec_root>

Ejemplo:
  deploy-operaciones-app.sh /home/bitnami/htdocs/desert/btec_v1

Este script copia la pantalla Operations App 360 y sus endpoints al cliente.
Luego activa o actualiza el modulo desde modulos-btec.php.
TXT
}

if [[ "${1:-}" == "-h" || "${1:-}" == "--help" ]]; then
  usage
  exit 0
fi

if [[ $# -lt 1 ]]; then
  usage
  exit 1
fi

client_root="${1%/}"
if [[ ! -d "$client_root" ]]; then
  echo "Error: client_btec_root no existe: $client_root" >&2
  exit 1
fi

if [[ ! -d "$client_root/func" ]]; then
  echo "Error: no se encontro carpeta func en: $client_root" >&2
  exit 1
fi

script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
core_root="$(cd "$script_dir/.." && pwd)"

if [[ -L "$client_root/.btec-core" || -d "$client_root/.btec-core" ]]; then
  release_root="$(cd "$client_root/.btec-core" && pwd)"
else
  release_root="$(cd "$core_root/current" && pwd)"
fi

package_root="$release_root/clients/operaciones-app/btec_v1"
if [[ ! -d "$package_root" ]]; then
  echo "Error: no se encontro package operaciones-app en: $package_root" >&2
  exit 1
fi

backup_if_different() {
  local source="$1"
  local target="$2"
  if [[ -f "$target" ]] && ! cmp -s "$source" "$target"; then
    cp "$target" "$target.btec-backup-$(date +%Y%m%d%H%M%S)"
  fi
}

mkdir -p "$client_root/func"

for relative_path in \
  "operaciones.php" \
  "func/operaciones_app_data.php" \
  "func/operaciones_app_action.php"
do
  source_file="$package_root/$relative_path"
  target_file="$client_root/$relative_path"
  if [[ ! -f "$source_file" ]]; then
    echo "Error: no existe archivo fuente: $source_file" >&2
    exit 1
  fi
  mkdir -p "$(dirname "$target_file")"
  backup_if_different "$source_file" "$target_file"
  cp "$source_file" "$target_file"
done

if command -v setfacl >/dev/null 2>&1; then
  setfacl -m u:daemon:rwx "$client_root" "$client_root/func" || true
  setfacl -d -m u:daemon:rwx "$client_root" "$client_root/func" || true
  setfacl -m u:daemon:rw \
    "$client_root/operaciones.php" \
    "$client_root/func/operaciones_app_data.php" \
    "$client_root/func/operaciones_app_action.php" 2>/dev/null || true
  echo "ACL daemon aplicadas para futuras instalaciones desde el panel."
else
  echo "Aviso: setfacl no esta disponible; los permisos web no fueron actualizados." >&2
fi

echo "Operations App 360 desplegada correctamente."
echo "Cliente btec: $client_root"
echo "Siguiente paso: activar el modulo operacion-dia-app desde $client_root/modulos-btec.php"
