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

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

Ejemplo:
  deploy-web-health.sh /home/bitnami/htdocs/desert/btec_v1

Este script copia el wrapper admin web-health.php al cliente.
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/web-health"
if [[ ! -d "$package_root" ]]; then
  echo "Error: no se encontro package web-health en: $package_root" >&2
  exit 1
fi

cp "$package_root/btec_v1/web-health.php" "$client_root/web-health.php"

if command -v setfacl >/dev/null 2>&1; then
  setfacl -m u:daemon:rw "$client_root/web-health.php" 2>/dev/null || true
fi

echo "Salud Web desplegado correctamente."
echo "Cliente btec: $client_root"
echo "Siguiente paso: activar el modulo desde $client_root/modulos-btec.php"
