#!/usr/bin/env bash
# One-time installer for the Bandjoun Community of Texas (BCT) website.
# Supports AlmaLinux / Rocky / RHEL 8-9 (dnf) and Ubuntu / Debian (apt).
#
#   sudo bash deploy/install.sh              # plain server: nginx in front (uses the bundled content/ folder)
#   sudo bash deploy/install.sh --no-nginx   # cPanel/WHM server: Apache proxies instead
#
# Installs to /opt/bct, runs as user "bct", listens on 127.0.0.1:<port from settings.ini, default 8085>.
set -euo pipefail

SRC_DIR="$(cd "$(dirname "$0")/.." && pwd)"
APP_DIR=/opt/bct
NO_NGINX=0
DATA_SRC=""
for arg in "$@"; do
  case "$arg" in
    --no-nginx) NO_NGINX=1 ;;
    *) DATA_SRC="$arg" ;;
  esac
done
# default: the content bundled in this package
[[ -z "$DATA_SRC" && -d "$SRC_DIR/content" ]] && DATA_SRC="$SRC_DIR/content"

if [[ $EUID -ne 0 ]]; then echo "Run with sudo (or as root)."; exit 1; fi
if [[ -z "$DATA_SRC" || ! -e "$DATA_SRC" ]]; then
  echo "Usage: sudo bash deploy/install.sh [--no-nginx]   (uses the bundled content/ folder)"; exit 1
fi
DATA_SRC="$(readlink -f "$DATA_SRC")"

# ---------------------------------------------------------------- packages
if command -v dnf >/dev/null 2>&1; then
  FAMILY=rhel
  echo "==> Installing packages (dnf)"
  dnf install -y -q python3.11 python3.11-pip rsync unzip tar policycoreutils-python-utils >/dev/null
  PY=python3.11
  [[ $NO_NGINX -eq 0 ]] && dnf install -y -q nginx >/dev/null
  # ffmpeg is optional (only used to make video thumbnails) – needs EPEL + RPM Fusion
  if ! command -v ffmpeg >/dev/null 2>&1; then
    echo "==> Trying to install ffmpeg (optional)"
    dnf install -y -q dnf-plugins-core epel-release >/dev/null 2>&1 || true
    dnf config-manager --set-enabled powertools >/dev/null 2>&1 || dnf config-manager --set-enabled crb >/dev/null 2>&1 || true
    dnf install -y -q --nogpgcheck "https://mirrors.rpmfusion.org/free/el/rpmfusion-free-release-$(rpm -E %rhel).noarch.rpm" >/dev/null 2>&1 || true
    dnf install -y -q ffmpeg >/dev/null 2>&1 || echo "    ffmpeg not installed – videos show a plain play tile instead of a thumbnail (everything else works)."
  fi
else
  FAMILY=debian
  echo "==> Installing packages (apt)"
  apt-get update -qq
  apt-get install -y -qq python3 python3-venv python3-pip rsync unzip ffmpeg >/dev/null
  [[ $NO_NGINX -eq 0 ]] && apt-get install -y -qq nginx >/dev/null
  PY=python3
fi

# ---------------------------------------------------------------- app files
echo "==> Creating user 'bct' and copying files to $APP_DIR"
id -u bct >/dev/null 2>&1 || useradd --system --home-dir "$APP_DIR" --shell /sbin/nologin bct
mkdir -p "$APP_DIR"
rsync -a --exclude /content --exclude instance --exclude uploads --exclude settings.ini --exclude venv --exclude __pycache__ "$SRC_DIR"/ "$APP_DIR"/
[[ -f "$APP_DIR/settings.ini" ]] || cp "$APP_DIR/settings.ini.example" "$APP_DIR/settings.ini"
mkdir -p "$APP_DIR/uploads" "$APP_DIR/instance"

echo "==> Python environment ($PY)"
$PY -m venv "$APP_DIR/venv"
"$APP_DIR/venv/bin/pip" install -q --upgrade pip
"$APP_DIR/venv/bin/pip" install -q -r "$APP_DIR/requirements.txt"
chown -R bct:bct "$APP_DIR"
chmod 755 "$APP_DIR"

echo "==> Importing content (texts, board, events, slideshow, photo galleries) – about a minute"
rm -rf /tmp/bct-content && mkdir -p /tmp/bct-content
cp -r "$DATA_SRC" /tmp/bct-content/ && chmod -R a+rX /tmp/bct-content
cd "$APP_DIR"
sudo -u bct "$APP_DIR/venv/bin/flask" --app app import-content /tmp/bct-content
rm -rf /tmp/bct-content

# ---------------------------------------------------------------- service
echo "==> systemd service 'bct'"
cp "$APP_DIR/deploy/bct.service" /etc/systemd/system/bct.service
systemctl daemon-reload
systemctl enable --now bct
sleep 2
systemctl is-active --quiet bct && echo "    bct service is running" || { echo "    bct failed to start:"; journalctl -u bct -n 30 --no-pager; exit 1; }

PORT=$(grep -E '^\s*port\s*=' "$APP_DIR/settings.ini" | head -1 | awk -F= '{gsub(/ /,"",$2); print $2}')

# ---------------------------------------------------------------- SELinux (RHEL family)
if [[ $FAMILY == rhel ]] && command -v getenforce >/dev/null 2>&1 && [[ "$(getenforce)" != "Disabled" ]]; then
  echo "==> SELinux: allow the web server to proxy to the app and read photos"
  setsebool -P httpd_can_network_connect 1
  semanage fcontext -a -t httpd_sys_content_t "$APP_DIR/(uploads|static)(/.*)?" 2>/dev/null || \
    semanage fcontext -m -t httpd_sys_content_t "$APP_DIR/(uploads|static)(/.*)?"
  restorecon -R "$APP_DIR/uploads" "$APP_DIR/static"
fi

# ---------------------------------------------------------------- nginx
if [[ $NO_NGINX -eq 0 ]]; then
  echo "==> nginx"
  sed "s#proxy_pass http://127.0.0.1:8085;#proxy_pass http://127.0.0.1:${PORT};#" "$APP_DIR/deploy/nginx-bct.conf" > /tmp/bct-nginx.conf
  if [[ -d /etc/nginx/sites-available ]]; then
    mv /tmp/bct-nginx.conf /etc/nginx/sites-available/bct
    ln -sf /etc/nginx/sites-available/bct /etc/nginx/sites-enabled/bct
  else
    mv /tmp/bct-nginx.conf /etc/nginx/conf.d/bct.conf
    [[ $FAMILY == rhel ]] && restorecon /etc/nginx/conf.d/bct.conf 2>/dev/null || true
  fi
  nginx -t
  systemctl enable --now nginx
  systemctl reload nginx
  if command -v firewall-cmd >/dev/null 2>&1 && systemctl is-active --quiet firewalld; then
    echo "==> firewalld: opening http/https"
    firewall-cmd --permanent --add-service=http --add-service=https >/dev/null
    firewall-cmd --reload >/dev/null
  fi
fi

echo
echo "Done. The BCT site is running on 127.0.0.1:${PORT}."
if [[ $NO_NGINX -eq 0 ]]; then
  echo "Next: point DNS to this server, then run certbot for HTTPS (see README)."
else
  echo "Next: add the Apache proxy include for the domain in WHM/cPanel (see README, 'cPanel servers')."
fi
