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

# Finalize Microweber-under-/mw in MySQL mode.
# Assumes `deploy_microweber_subdir.sh` already ran (Laravel tree at <site>/private/mw).
# Rewrites .env to MySQL and runs `php artisan microweber:install --db-driver=mysql`.
#
# Usage (per site):
#   bash finalize_mw_mysql.sh \
#     --site-root /srv/www/client/draytonlogistics \
#     --app-url 'https://draytonlogistics.work/mw' \
#     --app-brand 'Drayton Logistics' \
#     --db-name draytonlogistics_mw \
#     --db-user drayton_mw \
#     --db-pass '...' \
#     --cms-bridge-config /srv/www/client/draytonlogistics/private/app/config.local.php \
#     --cms-sso-secret '...' \
#     --admin-email you@example.com \
#     --admin-username mwadmin \
#     --admin-password 'ChooseStrong'

SITE_ROOT=""
APP_URL=""
APP_BRAND=""
DB_NAME=""
DB_USER=""
DB_PASS=""
CMS_BRIDGE=""
CMS_SSO=""
ADMIN_EMAIL=""
ADMIN_USER=""
ADMIN_PASS=""
DB_HOST="127.0.0.1"
DB_PORT="3306"
# Optional: post-install, switch the active site template to the named theme
# (must already exist under userfiles/templates/<name>/ — the rsync from
# CMS2/microweber in deploy_microweber_subdir.sh ships any theme bundled in
# source, so 'seethruit' is available out of the box on every install).
SITE_TEMPLATE=""

while (($#)); do
  case "$1" in
    --site-root) SITE_ROOT="${2:-}"; shift 2 ;;
    --app-url) APP_URL="${2:-}"; shift 2 ;;
    --app-brand) APP_BRAND="${2:-}"; shift 2 ;;
    --db-host) DB_HOST="${2:-}"; shift 2 ;;
    --db-port) DB_PORT="${2:-}"; shift 2 ;;
    --db-name) DB_NAME="${2:-}"; shift 2 ;;
    --db-user) DB_USER="${2:-}"; shift 2 ;;
    --db-pass) DB_PASS="${2:-}"; shift 2 ;;
    --cms-bridge-config) CMS_BRIDGE="${2:-}"; shift 2 ;;
    --cms-sso-secret) CMS_SSO="${2:-}"; shift 2 ;;
    --admin-email) ADMIN_EMAIL="${2:-}"; shift 2 ;;
    --admin-username) ADMIN_USER="${2:-}"; shift 2 ;;
    --admin-password) ADMIN_PASS="${2:-}"; shift 2 ;;
    --site-template) SITE_TEMPLATE="${2:-}"; shift 2 ;;
    *) echo "Unknown arg: $1" >&2; exit 1 ;;
  esac
done

for var in SITE_ROOT APP_URL APP_BRAND DB_NAME DB_USER DB_PASS CMS_BRIDGE CMS_SSO ADMIN_EMAIL ADMIN_USER ADMIN_PASS; do
  if [[ -z "${!var}" ]]; then
    echo "Error: --${var,,} (or matching flag) is required." >&2
    exit 1
  fi
done

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

APP_KEY=""
if [[ -f "$MW_ROOT/.env" ]]; then
  APP_KEY="$(grep -E '^APP_KEY=' "$MW_ROOT/.env" | head -n1 | cut -d= -f2- || true)"
fi
if [[ -z "$APP_KEY" ]]; then
  APP_KEY="$(cd "$MW_ROOT" && php -r "echo 'base64:'.base64_encode(random_bytes(32));")"
fi

umask 027
cat > "$MW_ROOT/.env" <<ENV
APP_NAME="${APP_BRAND} Microweber"
APP_ENV=production
APP_KEY=${APP_KEY}
APP_DEBUG=false
APP_URL=${APP_URL}

DB_CONNECTION=mysql
DB_HOST=${DB_HOST}
DB_PORT=${DB_PORT}
DB_DATABASE=${DB_NAME}
DB_USERNAME=${DB_USER}
DB_PASSWORD=${DB_PASS}

CACHE_DRIVER=file
SESSION_DRIVER=file
QUEUE_CONNECTION=sync

CMS_BRIDGE_CONFIG=${CMS_BRIDGE}
CMS_SSO_SECRET=${CMS_SSO}
ENV
chgrp www-data "$MW_ROOT/.env" 2>/dev/null || true
chmod 640 "$MW_ROOT/.env"

# Microweber's stock config/app.php uses getenv() which doesn't see .env under
# Apache mod_php; force the canonical Laravel env() helper so APP_KEY resolves.
if [[ -f "$MW_ROOT/config/app.php" ]]; then
  sed -i \
    -e "s#getenv('APP_KEY') ?: 'YourSecretKey!!!'#env('APP_KEY', 'YourSecretKey!!!')#" \
    -e "s#(bool) getenv('APP_DEBUG') ?: false#(bool) env('APP_DEBUG', false)#" \
    "$MW_ROOT/config/app.php"
fi

# Make Laravel-writable dirs readable+writable by Apache (www-data)
for D in storage bootstrap/cache userfiles config; 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

mysql --protocol=TCP -h "$DB_HOST" -P "$DB_PORT" -u "$DB_USER" -p"$DB_PASS" "$DB_NAME" \
  -e "SELECT 1" >/dev/null

cd "$MW_ROOT"
rm -f bootstrap/cache/config.php bootstrap/cache/routes-v7.php bootstrap/cache/services.php 2>/dev/null || true

if [[ -f config/microweber.php ]]; then
  php -r "\$f='config/microweber.php'; \$c=require \$f; if(is_array(\$c)){\$c['is_installed']=0; file_put_contents(\$f,\"<?php return \".var_export(\$c,true).\";\\n\");}"
else
  mkdir -p config
  cat > config/microweber.php <<'PHP'
<?php return array (
  'version' => '2.0.20',
  'compile_assets' => 1,
  'disable_model_cache' => 0,
  'has_admin' => 1,
  'is_installed' => 0,
);
PHP
fi

php artisan config:clear >/dev/null 2>&1 || true
php artisan cache:clear >/dev/null 2>&1 || true

php artisan microweber:install \
  --db-driver=mysql \
  --db-host="$DB_HOST" \
  --db-name="$DB_NAME" \
  --db-username="$DB_USER" \
  --db-password="$DB_PASS" \
  --db-prefix= \
  --email="$ADMIN_EMAIL" \
  --username="$ADMIN_USER" \
  --password="$ADMIN_PASS" \
  --default-content=0

# Production caches: write compiled routes/views/events into bootstrap/cache so
# every page render skips the per-request route + blade-compile work.
# bootstrap/cache and storage/framework are already group-www-data with setgid
# (see chmod loop above), so files emitted here remain Apache-writable.
#
# IMPORTANT: do NOT run `php artisan config:cache` against Microweber. MW
# registers a lot of config at runtime inside service providers (per-site
# overrides, dynamic module config, install-flow settings). With a compiled
# config.php, those providers run against a stale snapshot and the encrypter
# loses APP_KEY -- the visible symptom is "Unsupported cipher or incorrect
# key length" / 500 on every MW route. We tested it on this stack: only
# config:cache breaks MW; the other three are safe and give the same boot win.
php artisan optimize:clear >/dev/null 2>&1 || true
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

# Switch the active site template if requested. MW stores this in the options
# table (key='current_template', group='template') and TemplateInstaller seeds
# the row at install time, so an UPDATE here is always safe.
if [[ -n "$SITE_TEMPLATE" ]]; then
  TEMPLATE_DIR="$MW_ROOT/userfiles/templates/$SITE_TEMPLATE"
  if [[ ! -d "$TEMPLATE_DIR" ]]; then
    echo "Warning: --site-template '$SITE_TEMPLATE' set but $TEMPLATE_DIR does not exist."
    echo "         Skipping active-template switch."
  else
    mysql --protocol=TCP -h "$DB_HOST" -P "$DB_PORT" -u "$DB_USER" -p"$DB_PASS" "$DB_NAME" \
      -e "UPDATE options SET option_value='$SITE_TEMPLATE', updated_at=NOW() WHERE option_key='current_template' AND option_group='template';" >/dev/null
    echo "Active site template set to '$SITE_TEMPLATE'."
  fi
fi

echo "Microweber installed at $APP_URL (admin: $ADMIN_USER / $ADMIN_EMAIL)"
echo "Production caches written. To rebuild after a code change, run:"
echo "  bash $(dirname "$0")/rebuild_mw_caches.sh --site-root $SITE_ROOT"
