#!/usr/bin/env bash
set -euo pipefail

# Rebuild Laravel/Microweber production caches for a deployed site.
# Run this any time you sync source changes into <site>/private/mw/ outside of
# finalize_mw_mysql.sh (e.g. after deploy_microweber_subdir.sh re-rsyncs the
# Laravel tree on top of an existing install).
#
# Usage:
#   bash rebuild_mw_caches.sh --site-root /srv/www/seethruit
#   bash rebuild_mw_caches.sh --site-root /srv/www/client/draytonlogistics

SITE_ROOT=""

while (($#)); do
  case "$1" in
    --site-root) SITE_ROOT="${2:-}"; shift 2 ;;
    *) echo "Unknown arg: $1" >&2; exit 1 ;;
  esac
done

if [[ -z "$SITE_ROOT" || ! -d "$SITE_ROOT/private/mw" ]]; then
  echo "Error: --site-root must point to a site with private/mw/ deployed" >&2
  exit 1
fi

MW_ROOT="$SITE_ROOT/private/mw"
if [[ ! -f "$MW_ROOT/vendor/autoload.php" ]]; then
  echo "Error: $MW_ROOT/vendor/autoload.php missing — MW not installed yet" >&2
  exit 1
fi

cd "$MW_ROOT"

# Clear first so any stale cache from the previous deploy doesn't leak into
# the new compilation pass.
php artisan optimize:clear >/dev/null 2>&1 || true

# Rebuild the caches that are SAFE for Microweber.
#
# IMPORTANT: do NOT run `php artisan config:cache` against this app.
# Microweber registers a lot of config at runtime (per-site overrides, dynamic
# module config, install-flow settings) inside service providers. Once Laravel
# has a compiled bootstrap/cache/config.php, those service providers run with a
# stale snapshot and the encrypter ends up with no valid APP_KEY -- the visible
# symptom is "Unsupported cipher or incorrect key length" / 500 on every MW
# route. We tested this on this stack: only config:cache breaks MW; route:cache,
# view:cache, and event:cache are all safe and provide the same boot-time win.
php artisan route:cache     >/dev/null 2>&1 || true
php artisan view:cache      >/dev/null 2>&1 || true
php artisan event:cache     >/dev/null 2>&1 || true

# Make sure compiled caches stay www-data-writable (Blade view cache writes are
# the most common runtime failure when ownership drifts).
for D in bootstrap/cache storage/framework/views storage/framework/cache; do
  if [[ -d "$MW_ROOT/$D" ]]; then
    chgrp -R www-data "$MW_ROOT/$D" 2>/dev/null || true
    chmod -R ug+rwX  "$MW_ROOT/$D" 2>/dev/null || true
    find "$MW_ROOT/$D" -type d -exec chmod g+s {} + 2>/dev/null || true
  fi
done

echo "Rebuilt MW production caches under $MW_ROOT"
