#!/bin/bash
# Installation du service systemd — à exécuter sur le VPS : sudo bash deploy/install-service.sh
set -euo pipefail

APP_DIR="/var/www/stessy.org/copro_gestion"
SERVICE_NAME="copro_gestion"
GUNICORN="${APP_DIR}/venv/bin/gunicorn"

if [[ $EUID -ne 0 ]]; then
  echo "Relancez avec sudo : sudo bash deploy/install-service.sh"
  exit 1
fi

venv_broken() {
  [[ ! -f "${GUNICORN}" ]] && return 0
  local shebang
  shebang=$(head -1 "${GUNICORN}")
  [[ "${shebang}" != *"${APP_DIR}/venv/"* ]] && return 0
  ! "${GUNICORN}" --version &>/dev/null
}

if venv_broken; then
  echo "Environnement virtuel absent ou invalide (souvent après renommage du dossier papa → copro_gestion)."
  echo "Recréation de venv dans ${APP_DIR}…"
  if [[ -d "${APP_DIR}/venv" ]]; then
    rm -rf "${APP_DIR}/venv"
  fi
  python3 -m venv "${APP_DIR}/venv"
  "${APP_DIR}/venv/bin/pip" install --upgrade pip
  "${APP_DIR}/venv/bin/pip" install -r "${APP_DIR}/requirements.txt"
  chown -R www-data:www-data "${APP_DIR}/venv"
fi

if [[ ! -x "${GUNICORN}" ]]; then
  echo "Gunicorn introuvable dans ${APP_DIR}/venv"
  exit 1
fi

install -m 644 "${APP_DIR}/deploy/copro_gestion.service" "/etc/systemd/system/${SERVICE_NAME}.service"

mkdir -p "${APP_DIR}/data"
chown -R www-data:www-data "${APP_DIR}/data"

# Ancien nom de service (migration ponctuelle)
if systemctl is-enabled gunicorn-papa &>/dev/null; then
  systemctl stop gunicorn-papa 2>/dev/null || true
  systemctl disable gunicorn-papa 2>/dev/null || true
  rm -f /etc/systemd/system/gunicorn-papa.service
fi

systemctl daemon-reload
systemctl enable "${SERVICE_NAME}"
systemctl restart "${SERVICE_NAME}"
systemctl status "${SERVICE_NAME}" --no-pager

echo ""
echo "Service : ${SERVICE_NAME}"
echo "URL publique (pour l'instant) : https://www.stessy.org/papa/"
echo ""
echo "  sudo systemctl restart ${SERVICE_NAME}   # après modif Python"
echo "  sudo journalctl -u ${SERVICE_NAME} -f    # logs"
