#!/usr/bin/env bash
# Re-applies the (idempotent) schema, fixes permissions, and restarts the
# worker services. Run with sudo after pulling new code into place.
set -euo pipefail

APP_DIR="/var/www/html/barox-swtsim"

if [ "$(id -u)" -ne 0 ]; then
    echo "This script must be run as root: sudo scripts/update.sh" >&2
    exit 1
fi

if [ ! -f "${APP_DIR}/config/local.php" ]; then
    echo "config/local.php not found — run scripts/install.sh first." >&2
    exit 1
fi

DB_NAME=$(php -r '$c = require "'"${APP_DIR}"'/config/local.php"; echo $c["db"]["name"];')

echo "==> Re-applying schema (CREATE TABLE IF NOT EXISTS is idempotent)..."
mysql --user=root "${DB_NAME}" < "${APP_DIR}/sql/schema.sql"

echo "==> Fixing permissions..."
bash "${APP_DIR}/scripts/permissions.sh"

echo "==> Reloading Apache..."
apache2ctl configtest && systemctl reload apache2

echo "==> Restarting worker services..."
systemctl restart barox-snmp.service barox-scenario.service barox-trap.service

echo "==> Done. Service status:"
systemctl --no-pager status barox-snmp barox-scenario barox-trap | head -40
