#!/usr/bin/env bash
# mBlog — deploy an assembled staging tree to production (additive, safe).
# Does NOT run the database migration (that is a separate, deliberate step —
# see rehearse-migration.sh and DEPLOYMENT.md).
#
# Usage:
#   PROJECT_ROOT=/var/www/mblog APACHE_USER=apache ./deploy.sh /path/to/staging
#
# 'staging' must be a full project tree: web/  app/  config/  scripts/
# (Assemble it by unzipping the module bundles over a copy of the current site.)
set -euo pipefail

STAGING="${1:?usage: deploy.sh <staging-dir>}"
PROJECT_ROOT="${PROJECT_ROOT:-/var/www/mblog}"
APACHE_USER="${APACHE_USER:-apache}"
here="$(cd "$(dirname "$0")" && pwd)"

echo "==> Lint every PHP file in staging"
while IFS= read -r -d '' f; do
  php -l "$f" >/dev/null
done < <(find "$STAGING" -name '*.php' -print0)

echo "==> Backup current production"
PROJECT_ROOT="$PROJECT_ROOT" "$here/backup.sh"

echo "==> Sync staging -> $PROJECT_ROOT (additive; legacy files preserved)"
# No --delete: the legacy /api and user uploads must survive.
rsync -a \
  --exclude 'logs/*' \
  --exclude 'cache/*' \
  --exclude 'web/images/*' \
  --exclude 'backups/*' \
  --exclude 'config/local.php' \
  "$STAGING"/ "$PROJECT_ROOT"/

echo "==> Ensure writable runtime directories"
for d in logs cache web/images; do
  mkdir -p "$PROJECT_ROOT/$d"
  chown -R "$APACHE_USER" "$PROJECT_ROOT/$d" 2>/dev/null || true
  chmod -R 775 "$PROJECT_ROOT/$d"
done

echo
echo "Deploy synced. Next:"
echo "  1) Reload Apache if config changed:   systemctl reload httpd"
echo "  2) Run the health check:              ./healthcheck.sh https://mblog.in"
