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

# Local-first deploy script for homolog theme/plugin 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}"
SSH_KEY_PATH="${SSH_KEY_PATH:-$HOME/.ssh/gitlab-deploy}"
REMOTE_DEPLOY_WRAPPER="${REMOTE_DEPLOY_WRAPPER:-}"

DEPLOY_THEME="${DEPLOY_THEME:-1}"
DEPLOY_PLUGIN="${DEPLOY_PLUGIN:-1}"
LOCAL_THEME_DIR="${LOCAL_THEME_DIR:-wp-content/themes/ru-ufpe-theme}"
LOCAL_PLUGIN_DIR="${LOCAL_PLUGIN_DIR:-wp-content/plugins/ufpe-google-oidc}"
REMOTE_STAGE_DIR="${REMOTE_STAGE_DIR:-~/deploy/portal-ru3/wp-content/themes/ru-ufpe-theme}"
REMOTE_PLUGIN_STAGE_DIR="${REMOTE_PLUGIN_STAGE_DIR:-~/deploy/portal-ru3/wp-content/plugins/ufpe-google-oidc}"
REMOTE_THEME_DIR="${REMOTE_THEME_DIR:-/var/www/ru/wp-classic/wp-content/themes/ru-ufpe-theme}"
REMOTE_PLUGIN_DIR="${REMOTE_PLUGIN_DIR:-/var/www/ru/wp-classic/wp-content/plugins/ufpe-google-oidc}"
WP_PATH="${WP_PATH:-/var/www/ru/wp-classic}"
PLUGIN_SLUG="${PLUGIN_SLUG:-ufpe-google-oidc/ufpe-google-oidc.php}"
PLUGIN_STATUS_SLUG="${PLUGIN_STATUS_SLUG:-ufpe-google-oidc}"
ACTIVATE_PLUGIN="${ACTIVATE_PLUGIN:-0}"

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
  SSH_KEY_PATH
  REMOTE_DEPLOY_WRAPPER
  DEPLOY_THEME, DEPLOY_PLUGIN, ACTIVATE_PLUGIN
  LOCAL_THEME_DIR, REMOTE_STAGE_DIR, REMOTE_THEME_DIR
  LOCAL_PLUGIN_DIR, REMOTE_PLUGIN_STAGE_DIR, REMOTE_PLUGIN_DIR
  PLUGIN_SLUG, PLUGIN_STATUS_SLUG
  WP_PATH
EOF
  exit 0
fi

if [[ "$SSH_KEY_PATH" == "~/"* ]]; then
  SSH_KEY_PATH="$HOME/${SSH_KEY_PATH#~/}"
elif [[ "$SSH_KEY_PATH" == '$HOME/'* ]]; then
  SSH_KEY_PATH="$HOME/${SSH_KEY_PATH#\$HOME/}"
fi

if [[ ! -f "$SSH_KEY_PATH" ]]; then
  echo "SSH deploy key not found: $SSH_KEY_PATH" >&2
  exit 1
fi

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

if [[ "$DEPLOY_PLUGIN" == "1" && ! -d "$LOCAL_PLUGIN_DIR" ]]; then
  echo "Local plugin directory not found: $LOCAL_PLUGIN_DIR" >&2
  exit 1
fi

REMOTE_TARGET="${REMOTE_USER}@${REMOTE_HOST}"
SSH_BASE=(
  ssh
  -i "$SSH_KEY_PATH"
  -o BatchMode=yes
  -o IdentitiesOnly=yes
)

printf -v RSYNC_SSH '%q ' "${SSH_BASE[@]}"
REMOTE_HOME=''

remote_home() {
  if [[ -z "$REMOTE_HOME" ]]; then
    REMOTE_HOME="$("${SSH_BASE[@]}" "$REMOTE_TARGET" "printf %s \"\$HOME\"")"
  fi

  printf '%s\n' "$REMOTE_HOME"
}

expand_remote_path() {
  local path="$1"
  local home

  if [[ "$path" == "~/"* ]]; then
    home="$(remote_home)"
    printf '%s/%s\n' "$home" "${path#~/}"
    return
  fi

  printf '%s\n' "$path"
}

require_remote_passwordless_sudo() {
  if ! "${SSH_BASE[@]}" "$REMOTE_TARGET" "sudo -n true" >/dev/null 2>&1; then
    echo "Remote sudo requires a password for $REMOTE_TARGET." >&2
    echo "Configure passwordless sudo for the deploy user before using this script." >&2
    exit 1
  fi
}

require_remote_deploy_wrapper() {
  if [[ -z "$REMOTE_DEPLOY_WRAPPER" ]]; then
    return 0
  fi

  if [[ "$DEPLOY_THEME" == "1" ]]; then
    echo "REMOTE_DEPLOY_WRAPPER only supports plugin-only deploys in this script." >&2
    exit 1
  fi

  if ! "${SSH_BASE[@]}" "$REMOTE_TARGET" \
    "sudo -n '$REMOTE_DEPLOY_WRAPPER' --self-check" >/dev/null 2>&1; then
    echo "Remote deploy wrapper is unavailable for $REMOTE_TARGET: $REMOTE_DEPLOY_WRAPPER" >&2
    echo "Install the wrapper and sudoers entry before using wrapper mode." >&2
    exit 1
  fi
}

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 files to remote home"
else
  echo "[apply] staging files to remote home"
fi

if [[ "$DEPLOY_THEME" == "1" ]]; then
  "${SSH_BASE[@]}" "$REMOTE_TARGET" "mkdir -p '$REMOTE_STAGE_DIR'"
  rsync -e "$RSYNC_SSH" "${RSYNC_COMMON[@]}" \
    "$LOCAL_THEME_DIR/" \
    "$REMOTE_TARGET:$REMOTE_STAGE_DIR/"
fi

if [[ "$DEPLOY_PLUGIN" == "1" ]]; then
  "${SSH_BASE[@]}" "$REMOTE_TARGET" "mkdir -p '$REMOTE_PLUGIN_STAGE_DIR'"
  rsync -e "$RSYNC_SSH" "${RSYNC_COMMON[@]}" \
    "$LOCAL_PLUGIN_DIR/" \
    "$REMOTE_TARGET:$REMOTE_PLUGIN_STAGE_DIR/"
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 files to web root"
else
  echo "[apply] promoting staged files to web root"
fi

if [[ -n "$REMOTE_DEPLOY_WRAPPER" ]]; then
  require_remote_deploy_wrapper
else
  require_remote_passwordless_sudo
fi

if [[ "$DEPLOY_THEME" == "1" ]]; then
  "${SSH_BASE[@]}" "$REMOTE_TARGET" \
    "set -euo pipefail; \
     sudo -n rsync $PROMOTE_FLAGS '$REMOTE_STAGE_DIR/' '$REMOTE_THEME_DIR/'"
fi

if [[ "$DEPLOY_PLUGIN" == "1" ]]; then
  if [[ -n "$REMOTE_DEPLOY_WRAPPER" ]]; then
    WRAPPER_STAGE_DIR="$(expand_remote_path "$REMOTE_PLUGIN_STAGE_DIR")"
    WRAPPER_PLUGIN_DIR="$(expand_remote_path "$REMOTE_PLUGIN_DIR")"
    WRAPPER_ARGS=(
      "$REMOTE_DEPLOY_WRAPPER"
      "$WRAPPER_STAGE_DIR"
      "$WRAPPER_PLUGIN_DIR"
      "$WP_PATH"
      "$PLUGIN_STATUS_SLUG"
    )

    if [[ "$DRY_RUN" == "1" ]]; then
      WRAPPER_ARGS=( "$REMOTE_DEPLOY_WRAPPER" --dry-run "$WRAPPER_STAGE_DIR" "$WRAPPER_PLUGIN_DIR" "$WP_PATH" "$PLUGIN_STATUS_SLUG" )
    fi

    printf -v WRAPPER_CMD '%q ' "${WRAPPER_ARGS[@]}"
    "${SSH_BASE[@]}" "$REMOTE_TARGET" "set -euo pipefail; sudo -n $WRAPPER_CMD"
  else
    "${SSH_BASE[@]}" "$REMOTE_TARGET" \
      "set -euo pipefail; \
       sudo -n mkdir -p '$REMOTE_PLUGIN_DIR'; \
       sudo -n rsync $PROMOTE_FLAGS '$REMOTE_PLUGIN_STAGE_DIR/' '$REMOTE_PLUGIN_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"
if [[ -z "$REMOTE_DEPLOY_WRAPPER" ]]; then
  "${SSH_BASE[@]}" "$REMOTE_TARGET" \
    "set -euo pipefail; \
     if [ '$DEPLOY_THEME' = '1' ]; then sudo -n find '$REMOTE_THEME_DIR' -type d -exec chmod 755 {} \\\;; fi; \
     if [ '$DEPLOY_THEME' = '1' ]; then sudo -n find '$REMOTE_THEME_DIR' -type f -exec chmod 644 {} \\\;; fi; \
     if [ '$DEPLOY_PLUGIN' = '1' ]; then sudo -n find '$REMOTE_PLUGIN_DIR' -type d -exec chmod 755 {} \\\;; fi; \
     if [ '$DEPLOY_PLUGIN' = '1' ]; then sudo -n find '$REMOTE_PLUGIN_DIR' -type f -exec chmod 644 {} \\\;; fi; \
     if [ '$DEPLOY_THEME' = '1' ]; then sudo -n restorecon -Rv '$REMOTE_THEME_DIR' >/dev/null 2>&1 || true; fi; \
     if [ '$DEPLOY_PLUGIN' = '1' ]; then sudo -n restorecon -Rv '$REMOTE_PLUGIN_DIR' >/dev/null 2>&1 || true; fi; \
     if [ '$DEPLOY_PLUGIN' = '1' ] && [ '$ACTIVATE_PLUGIN' = '1' ]; then sudo -n -u apache -H wp --path='$WP_PATH' plugin activate '$PLUGIN_SLUG'; fi; \
     sudo -n -u apache -H wp --path='$WP_PATH' cache flush; \
     if [ '$DEPLOY_PLUGIN' = '1' ]; then sudo -n -u apache -H wp --path='$WP_PATH' plugin is-installed '$PLUGIN_STATUS_SLUG'; fi; \
     if [ '$DEPLOY_PLUGIN' = '1' ]; then sudo -n -u apache -H wp --path='$WP_PATH' plugin status '$PLUGIN_STATUS_SLUG'; fi;"
fi

"${SSH_BASE[@]}" "$REMOTE_TARGET" \
  "set -euo pipefail; \
   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/ru-ufpe-theme/assets/images/illustrations/bandejao.png' | head -n 1; \
   curl -sSI -H 'Host: $HOST_HEADER' 'http://127.0.0.1/wp-content/themes/ru-ufpe-theme/assets/images/brand/institutional/institutional-signature-horizontal.svg' | head -n 1"

echo "Deploy complete."
