#!/bin/bash
# install.sh — First-time install on the remote SERVER (after deploy.sh)
# Author: Dr Hamid MADANI <drmdh@msn.com>
#
#   ssh user@server "cd /var/www/media-studio && ./install.sh"
#
# Performs : npm install + Next.js build + Apache vhost + TLS cert + PM2 start.
# Reads .env.deploy for DOMAIN / EMAIL / PORT.

set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
cd "${SCRIPT_DIR}"

if [ -f .env.deploy ]; then
  set -a; . ./.env.deploy; set +a
else
  echo "✗ .env.deploy not found on remote — run deploy.sh from your laptop first."
  exit 1
fi

DOMAIN="${DEPLOY_DOMAIN:?missing DEPLOY_DOMAIN in .env.deploy}"
EMAIL="${DEPLOY_EMAIL:-admin@example.com}"
PORT="${DEPLOY_PORT:-4499}"

CYAN='\033[0;36m'; GREEN='\033[0;32m'; YELLOW='\033[1;33m'; RED='\033[0;31m'; NC='\033[0m'

echo -e "${CYAN}══════════════════════════════════════════════════${NC}"
echo -e "${CYAN}  media-studio — Server install (${DOMAIN})         ${NC}"
echo -e "${CYAN}══════════════════════════════════════════════════${NC}"

# ── 1. Pre-flight ──────────────────────────────────────────────────────────
echo -e "\n${CYAN}[1/6] Pre-flight...${NC}"
command -v node >/dev/null 2>&1 || { echo -e "${RED}  ✗ node missing${NC}"; exit 1; }
echo -e "${GREEN}  ✓ Node $(node -v)${NC}"
if ! command -v ffmpeg >/dev/null 2>&1; then
  echo -e "${YELLOW}  ⚠ ffmpeg missing — installing...${NC}"
  sudo apt update && sudo apt install -y ffmpeg
fi
echo -e "${GREEN}  ✓ ffmpeg $(ffmpeg -version | head -1 | awk '{print $3}')${NC}"

# .env runtime — copy .env.example only if missing
if [ ! -f .env ] && [ -f .env.example ]; then
  cp .env.example .env
  echo -e "${YELLOW}  ⚠ .env seeded from .env.example — edit it now if you need to${NC}"
fi

# ── 2. npm install ─────────────────────────────────────────────────────────
echo -e "\n${CYAN}[2/6] npm install...${NC}"
npm install --legacy-peer-deps 2>&1 | tail -5

# ── 3. Next.js build ───────────────────────────────────────────────────────
echo -e "\n${CYAN}[3/6] Next.js production build...${NC}"
rm -rf .next
npm run build 2>&1 | tail -8

# ── 4. Apache vhost ────────────────────────────────────────────────────────
echo -e "\n${CYAN}[4/6] Apache vhost ${DOMAIN}...${NC}"
VHOST_FILE="/etc/apache2/sites-available/${DOMAIN}.conf"
if [ -f "${VHOST_FILE}" ]; then
  echo -e "${YELLOW}  ⚠ ${VHOST_FILE} already present — skip${NC}"
else
  if [ ! -f apache/vhost.template.conf ]; then
    echo -e "${RED}  ✗ apache/vhost.template.conf missing${NC}"; exit 1
  fi
  # Render template — substitute ${DOMAIN}, ${EMAIL}, ${PORT}; leave ${APACHE_LOG_DIR}.
  sudo bash -c "DOMAIN='${DOMAIN}' EMAIL='${EMAIL}' PORT='${PORT}' \
    envsubst '\${DOMAIN} \${EMAIL} \${PORT}' < apache/vhost.template.conf > ${VHOST_FILE}"
  sudo a2enmod proxy proxy_http proxy_wstunnel rewrite headers ssl 2>&1 | tail -2
  sudo a2ensite "${DOMAIN}.conf" 2>&1 | tail -1
  # Reload only if the cert already exists, else certbot will reload.
  if [ -f "/etc/letsencrypt/live/${DOMAIN}/fullchain.pem" ]; then
    sudo systemctl reload apache2
  fi
  echo -e "${GREEN}  ✓ vhost installed${NC}"
fi

# ── 5. TLS via certbot ─────────────────────────────────────────────────────
echo -e "\n${CYAN}[5/6] TLS cert via certbot...${NC}"
if [ -f "/etc/letsencrypt/live/${DOMAIN}/fullchain.pem" ]; then
  echo -e "${YELLOW}  ⚠ cert already issued — skip${NC}"
else
  # Temporarily replace vhost with a minimal :80-only config so the ACME
  # http-01 challenge isn't redirected to https before the cert exists.
  sudo cp "${VHOST_FILE}" "/tmp/${DOMAIN}.conf.bak"
  sudo bash -c "cat > ${VHOST_FILE} <<EOF
<VirtualHost *:80>
    ServerName ${DOMAIN}
    DocumentRoot /var/www/html
</VirtualHost>
EOF"
  sudo systemctl reload apache2
  sudo certbot certonly --webroot -w /var/www/html -d "${DOMAIN}" \
    --non-interactive --agree-tos -m "${EMAIL}" 2>&1 | tail -8 || \
    echo -e "${YELLOW}  ⚠ certbot failed — verify DNS A=${DOMAIN}→server-ip + no AAAA${NC}"
  # Restore the full vhost (now SSL cert exists).
  sudo cp "/tmp/${DOMAIN}.conf.bak" "${VHOST_FILE}"
  sudo systemctl reload apache2
fi

# ── 6. PM2 start ───────────────────────────────────────────────────────────
echo -e "\n${CYAN}[6/6] PM2 start media-studio...${NC}"
mkdir -p logs data
pm2 delete media-studio 2>/dev/null || true
pm2 start ecosystem.config.cjs
pm2 save

# ── Verify ─────────────────────────────────────────────────────────────────
sleep 3
LOCAL_CODE=$(curl -s -o /dev/null -w '%{http_code}' "http://127.0.0.1:${PORT}/" 2>/dev/null || echo "000")
PUBLIC_CODE=$(curl -s -o /dev/null -w '%{http_code}' "https://${DOMAIN}/" --max-time 8 2>/dev/null || echo "000")

echo ""
echo -e "${GREEN}══════════════════════════════════════════════════${NC}"
echo -e "${GREEN}  Install done                                     ${NC}"
echo -e "${GREEN}    Backend (127.0.0.1:${PORT}) : HTTP ${LOCAL_CODE}              ${NC}"
echo -e "${GREEN}    Public  (${DOMAIN})  : HTTP ${PUBLIC_CODE}                  ${NC}"
echo -e "${GREEN}══════════════════════════════════════════════════${NC}"
