#!/usr/bin/env bash
# Update an existing BCT website install with a new version of the code.
# Keeps all content: database (instance/), photos (uploads/), settings.ini and the Python venv.
#
#   unzip bct-website.zip && cd bct-website
#   sudo bash deploy/update.sh
set -euo pipefail

APP_DIR=/opt/bct
SRC_DIR="$(cd "$(dirname "$0")/.." && pwd)"

if [[ $EUID -ne 0 ]]; then echo "Run with sudo."; exit 1; fi
if [[ ! -d "$APP_DIR/venv" ]]; then echo "No install found in $APP_DIR — run deploy/install.sh first."; exit 1; fi

echo "==> Copying new code to $APP_DIR (content, photos and settings are kept)"
rsync -a --exclude /content --exclude instance --exclude uploads --exclude settings.ini --exclude venv --exclude __pycache__ \
  "$SRC_DIR"/ "$APP_DIR"/

echo "==> Updating Python packages"
"$APP_DIR/venv/bin/pip" install -q -r "$APP_DIR/requirements.txt"
chown -R bct:bct "$APP_DIR"

if command -v restorecon >/dev/null 2>&1; then
  restorecon -R "$APP_DIR/static" "$APP_DIR/uploads" 2>/dev/null || true
fi

echo "==> Restarting the site"
systemctl restart bct
sleep 2
if systemctl is-active --quiet bct; then
  echo "Done. The BCT website is running the new version."
else
  echo "The service did not start:"; journalctl -u bct -n 30 --no-pager; exit 1
fi
