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

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

usage() {
  cat <<'EOF'
Usage:
  ru-homolog-deploy-plugin --self-check
  ru-homolog-deploy-plugin [--dry-run] <stage_dir> <plugin_dir> <wp_path> <plugin_slug>
EOF
}

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

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

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

STAGE_DIR="$1"
PLUGIN_DIR="$2"
WP_PATH="$3"
PLUGIN_SLUG="$4"

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

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

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

mkdir -p "$PLUGIN_DIR"
rsync "${RSYNC_FLAGS[@]}" "$STAGE_DIR/" "$PLUGIN_DIR/"

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

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

sudo -u apache -H "$WP_BIN" --path="$WP_PATH" cache flush
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"
