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

WP_BIN="${WP_BIN:-/usr/local/bin/wp}"

usage() {
  cat <<'EOF'
Usage:
  ru-prod-deploy-release --self-check
  ru-prod-deploy-release [--dry-run] <theme_stage_dir> <theme_dir> <plugin_stage_dir> <plugin_dir> <wp_path> <plugin_slug> <deploy_theme> <deploy_plugin>
EOF
}

if [[ "${1:-}" == "--self-check" ]]; then
  exit 0
fi

DRY_RUN=0
if [[ "${1:-}" == "--dry-run" ]]; then
  DRY_RUN=1
  shift
fi

if [[ "$#" -ne 8 ]]; then
  usage >&2
  exit 64
fi

THEME_STAGE_DIR="$1"
THEME_DIR="$2"
PLUGIN_STAGE_DIR="$3"
PLUGIN_DIR="$4"
WP_PATH="$5"
PLUGIN_SLUG="$6"
DEPLOY_THEME="$7"
DEPLOY_PLUGIN="$8"

if [[ "$DEPLOY_THEME" != "0" && "$DEPLOY_THEME" != "1" ]]; then
  echo "DEPLOY_THEME must be 0 or 1" >&2
  exit 64
fi

if [[ "$DEPLOY_PLUGIN" != "0" && "$DEPLOY_PLUGIN" != "1" ]]; then
  echo "DEPLOY_PLUGIN must be 0 or 1" >&2
  exit 64
fi

RSYNC_FLAGS=(
  -avh
  --delete
  --omit-dir-times
  --no-perms
  --no-owner
  --no-group
)

if [[ "$DRY_RUN" == "1" ]]; then
  RSYNC_FLAGS+=( -n )
fi

if [[ "$DEPLOY_THEME" == "1" ]]; then
  [[ -d "$THEME_STAGE_DIR" ]] || { echo "Theme stage directory not found: $THEME_STAGE_DIR" >&2; exit 1; }
  mkdir -p "$THEME_DIR"
  rsync "${RSYNC_FLAGS[@]}" "$THEME_STAGE_DIR/" "$THEME_DIR/"
fi

if [[ "$DEPLOY_PLUGIN" == "1" ]]; then
  [[ -d "$PLUGIN_STAGE_DIR" ]] || { echo "Plugin stage directory not found: $PLUGIN_STAGE_DIR" >&2; exit 1; }
  mkdir -p "$PLUGIN_DIR"
  rsync "${RSYNC_FLAGS[@]}" "$PLUGIN_STAGE_DIR/" "$PLUGIN_DIR/"
fi

if [[ "$DRY_RUN" == "1" ]]; then
  exit 0
fi

if [[ "$DEPLOY_THEME" == "1" ]]; then
  find "$THEME_DIR" -type d -exec chmod 755 {} \;
  find "$THEME_DIR" -type f -exec chmod 644 {} \;
  restorecon -Rv "$THEME_DIR" >/dev/null 2>&1 || true
fi

if [[ "$DEPLOY_PLUGIN" == "1" ]]; then
  find "$PLUGIN_DIR" -type d -exec chmod 755 {} \;
  find "$PLUGIN_DIR" -type f -exec chmod 644 {} \;
  restorecon -Rv "$PLUGIN_DIR" >/dev/null 2>&1 || true
fi

sudo -u apache -H "$WP_BIN" --path="$WP_PATH" cache flush

if [[ "$DEPLOY_PLUGIN" == "1" ]]; then
  sudo -u apache -H "$WP_BIN" --path="$WP_PATH" plugin is-installed "$PLUGIN_SLUG"
  sudo -u apache -H "$WP_BIN" --path="$WP_PATH" plugin status "$PLUGIN_SLUG"
fi
