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

# Local-first deploy script for homolog theme sync.
# Default mode is dry-run. Use --apply to perform changes.

REMOTE_USER="${REMOTE_USER:-06215350443}"
REMOTE_HOST="${REMOTE_HOST:-150.161.0.230}"
HOST_HEADER="${HOST_HEADER:-ru-homolog.ufpe.br}"

LOCAL_THEME_DIR="${LOCAL_THEME_DIR:-wp-content/themes/ru-ufpe-theme}"
THEME_SLUG="${THEME_SLUG:-ru-ufpe-theme}"
REMOTE_STAGE_DIR="${REMOTE_STAGE_DIR:-~/deploy/portal-ru3/wp-content/themes/ru-ufpe-theme}"
REMOTE_THEME_DIR="${REMOTE_THEME_DIR:-/var/www/html/ru/wp-content/themes/ru-ufpe-theme}"
WP_PATH="${WP_PATH:-/var/www/html/ru}"
WEB_USER="${WEB_USER:-apache}"
WP_CLI_BIN="${WP_CLI_BIN:-wp}"

DRY_RUN=1
if [[ "${1:-}" == "--apply" ]]; then
  DRY_RUN=0
elif [[ "${1:-}" == "--help" ]]; then
  cat <<'EOF'
Usage:
  scripts/deploy-homolog-theme.sh           # dry-run (default)
  scripts/deploy-homolog-theme.sh --apply   # execute deploy

Optional environment overrides:
  REMOTE_USER, REMOTE_HOST, HOST_HEADER
  LOCAL_THEME_DIR, THEME_SLUG, REMOTE_STAGE_DIR, REMOTE_THEME_DIR, WP_PATH, WEB_USER, WP_CLI_BIN
EOF
  exit 0
fi

if [[ ! -d "$LOCAL_THEME_DIR" ]]; then
  echo "Local theme directory not found: $LOCAL_THEME_DIR" >&2
  exit 1
fi

REMOTE_TARGET="${REMOTE_USER}@${REMOTE_HOST}"

RSYNC_COMMON=(
  -avz
  --delete
  --omit-dir-times
  --no-perms
  --no-owner
  --no-group
)

if [[ "$DRY_RUN" == "1" ]]; then
  RSYNC_COMMON+=( -n )
  echo "[dry-run] staging theme to remote home"
else
  echo "[apply] staging theme to remote home"
fi

ssh "$REMOTE_TARGET" "mkdir -p '$REMOTE_STAGE_DIR'"
if ssh "$REMOTE_TARGET" "command -v rsync >/dev/null 2>&1"; then
  rsync "${RSYNC_COMMON[@]}" \
    "$LOCAL_THEME_DIR/" \
    "$REMOTE_TARGET:$REMOTE_STAGE_DIR/"
else
  echo "[info] remote rsync not found; using tar over ssh for staging"
  if [[ "$DRY_RUN" == "1" ]]; then
    tar -C "$LOCAL_THEME_DIR" -cf - . | ssh "$REMOTE_TARGET" "tar -tf - >/dev/null"
  else
    ssh "$REMOTE_TARGET" "find '$REMOTE_STAGE_DIR' -mindepth 1 -maxdepth 1 -exec rm -rf {} +"
    tar -C "$LOCAL_THEME_DIR" -cf - . | ssh "$REMOTE_TARGET" "tar -xf - -C '$REMOTE_STAGE_DIR'"
  fi
fi

PROMOTE_FLAGS="-avh --delete --omit-dir-times --no-perms --no-owner --no-group"
if [[ "$DRY_RUN" == "1" ]]; then
  PROMOTE_FLAGS="$PROMOTE_FLAGS -n"
  echo "[dry-run] promoting staged theme to web root"
else
  echo "[apply] promoting staged theme to web root"
fi

ssh "$REMOTE_TARGET" \
  "set -euo pipefail; \
   if command -v rsync >/dev/null 2>&1; then \
     sudo rsync $PROMOTE_FLAGS '$REMOTE_STAGE_DIR/' '$REMOTE_THEME_DIR/'; \
   else \
     echo '[info] remote rsync not found; using cp for promotion'; \
     sudo mkdir -p '$REMOTE_THEME_DIR'; \
     if [[ '$DRY_RUN' == '1' ]]; then \
       find '$REMOTE_STAGE_DIR' -mindepth 1 -maxdepth 2 -print | sed 's#^#[dry-run] would promote #'; \
     else \
       sudo find '$REMOTE_THEME_DIR' -mindepth 1 -maxdepth 1 -exec rm -rf {} +; \
       sudo cp -a '$REMOTE_STAGE_DIR/.' '$REMOTE_THEME_DIR/'; \
     fi; \
   fi"

if [[ "$DRY_RUN" == "1" ]]; then
  echo "Dry-run finished. Re-run with --apply to execute deploy."
  exit 0
fi

echo "[apply] running post-deploy checks"
ssh "$REMOTE_TARGET" \
  "THEME_SLUG='$THEME_SLUG' REMOTE_THEME_DIR='$REMOTE_THEME_DIR' WP_PATH='$WP_PATH' WEB_USER='$WEB_USER' WP_CLI_BIN='$WP_CLI_BIN' HOST_HEADER='$HOST_HEADER' bash -s" <<'REMOTE_SCRIPT'
set -euo pipefail

THEME_ROOT=$(dirname "$REMOTE_THEME_DIR")
sudo chmod -R u=rwX,go=rX "$REMOTE_THEME_DIR"
sudo restorecon -Rv "$REMOTE_THEME_DIR" >/dev/null 2>&1 || true

if command -v "$WP_CLI_BIN" >/dev/null 2>&1; then
  sudo -u "$WEB_USER" -H "$WP_CLI_BIN" --path="$WP_PATH" cache flush
  sudo -u "$WEB_USER" -H "$WP_CLI_BIN" --path="$WP_PATH" theme activate "$THEME_SLUG"
  sudo -u "$WEB_USER" -H "$WP_CLI_BIN" --path="$WP_PATH" theme list
else
  echo "[info] wp-cli not found; activating theme via WordPress bootstrap"
  sudo -u "$WEB_USER" -H env WP_PATH="$WP_PATH" THEME_SLUG="$THEME_SLUG" php <<'PHP'
<?php
define('WP_USE_THEMES', false);
require getenv('WP_PATH') . '/wp-load.php';
switch_theme(getenv('THEME_SLUG'));
if (function_exists('wp_cache_flush')) {
    wp_cache_flush();
}
echo 'Active theme: ' . wp_get_theme()->get_stylesheet() . PHP_EOL;
PHP
fi

sudo find "$THEME_ROOT" -mindepth 1 -maxdepth 1 -type d ! -name "$THEME_SLUG" -exec rm -rf {} +

echo '== Theme directories =='
sudo find "$THEME_ROOT" -mindepth 1 -maxdepth 1 -type d -printf '%f\n'

echo '== HTTP checks =='
curl -sSI -H "Host: $HOST_HEADER" 'http://127.0.0.1/' | head -n 1
curl -sSI -H "Host: $HOST_HEADER" "http://127.0.0.1/wp-content/themes/$THEME_SLUG/assets/images/illustrations/bandejao.png" | head -n 1
curl -sSI -H "Host: $HOST_HEADER" "http://127.0.0.1/wp-content/themes/$THEME_SLUG/assets/images/brand/institutional/institutional-signature-horizontal.svg" | head -n 1
REMOTE_SCRIPT

echo "Deploy complete."
