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

PLUGIN_SLUG="o2-location-text-assistant"
SVN_USERNAME="yotani"
SVN_URL="https://plugins.svn.wordpress.org/${PLUGIN_SLUG}"
PUBLIC_URL="https://wordpress.org/plugins/${PLUGIN_SLUG}/"

PLUGIN_DIR="/Users/yuichiro/Documents/wordpress/wp-content/plugins/${PLUGIN_SLUG}"
SVN_DIR="/Users/yuichiro/Documents/wordpress-svn/${PLUGIN_SLUG}"

die() {
  printf "\nERROR: %s\n" "$*" >&2
  exit 1
}

on_error() {
  printf "\nDeployment failed at line %s.\n" "$1" >&2
  printf "If WordPress.org commit access is not active yet, wait until the one-hour activation window has passed and run this script again.\n" >&2
}
trap 'on_error "$LINENO"' ERR

printf "\n=== O2 Location Text Assistant: WordPress.org deploy ===\n\n"

# 1. Install Homebrew when necessary, then install SVN.
if ! command -v brew >/dev/null 2>&1; then
  printf "Homebrew was not found. Installing Homebrew...\n"
  /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

  if [[ -x /opt/homebrew/bin/brew ]]; then
    eval "$(/opt/homebrew/bin/brew shellenv)"
  elif [[ -x /usr/local/bin/brew ]]; then
    eval "$(/usr/local/bin/brew shellenv)"
  else
    die "Homebrew installation completed, but brew could not be located."
  fi
fi

if ! command -v svn >/dev/null 2>&1; then
  printf "SVN was not found. Installing Subversion with Homebrew...\n"
  brew install subversion
fi

# Ensure Homebrew's Subversion takes precedence.
SVN_PREFIX="$(brew --prefix subversion 2>/dev/null || true)"
if [[ -n "$SVN_PREFIX" && -x "$SVN_PREFIX/bin/svn" ]]; then
  export PATH="$SVN_PREFIX/bin:$PATH"
fi

command -v svn >/dev/null 2>&1 || die "SVN installation failed."
printf "SVN: %s (%s)\n" "$(command -v svn)" "$(svn --version --quiet)"

# 2. Validate the local plugin.
[[ -d "$PLUGIN_DIR" ]] || die "Plugin directory not found: $PLUGIN_DIR"
[[ -f "$PLUGIN_DIR/readme.txt" ]] || die "readme.txt not found in: $PLUGIN_DIR"

MAIN_FILE="$PLUGIN_DIR/${PLUGIN_SLUG}.php"
if [[ ! -f "$MAIN_FILE" ]]; then
  MAIN_FILE="$(
    find "$PLUGIN_DIR" -maxdepth 1 -type f -name '*.php' -print0 |
      while IFS= read -r -d '' file; do
        if grep -qi '^[[:space:]]*\*[^:]*Plugin Name[[:space:]]*:' "$file"; then
          printf '%s\n' "$file"
          break
        fi
      done
  )"
fi
[[ -n "${MAIN_FILE:-}" && -f "$MAIN_FILE" ]] || die "Main plugin PHP file could not be detected."

VERSION="$(
  sed -nE 's/^[[:space:]]*\*?[[:space:]]*Version:[[:space:]]*([0-9]+(\.[0-9]+)+).*$/\1/p' "$MAIN_FILE" |
    head -n 1
)"
STABLE_TAG="$(
  awk '
    BEGIN { IGNORECASE = 1 }
    /^[[:space:]]*Stable[[:space:]]+tag[[:space:]]*:/ {
      line = $0
      sub(/^[^:]*:[[:space:]]*/, "", line)
      sub(/[[:space:]].*$/, "", line)
      print line
      exit
    }
  ' "$PLUGIN_DIR/readme.txt"
)"

[[ -n "$VERSION" ]] || die "A numeric Version header was not found in: $MAIN_FILE"
[[ -n "$STABLE_TAG" ]] || die "A numeric Stable tag was not found in readme.txt. Add a line such as: Stable tag: $VERSION"
[[ "$VERSION" == "$STABLE_TAG" ]] ||
  die "Version mismatch: PHP Version=$VERSION, readme.txt Stable Tag=$STABLE_TAG"

printf "Plugin source: %s\n" "$PLUGIN_DIR"
printf "Main file:     %s\n" "$(basename "$MAIN_FILE")"
printf "Release:       %s\n\n" "$VERSION"

# 3. Check out or update the WordPress.org SVN repository.
mkdir -p "$(dirname "$SVN_DIR")"

if [[ -d "$SVN_DIR/.svn" ]]; then
  printf "Updating existing SVN working copy...\n"
  svn update "$SVN_DIR" --username "$SVN_USERNAME"
else
  if [[ -e "$SVN_DIR" ]]; then
    die "SVN destination already exists but is not an SVN working copy: $SVN_DIR"
  fi
  printf "Checking out WordPress.org SVN repository...\n"
  svn checkout "$SVN_URL" "$SVN_DIR" --username "$SVN_USERNAME"
fi

mkdir -p "$SVN_DIR/trunk" "$SVN_DIR/tags" "$SVN_DIR/assets"

# Published tags are immutable. Never overwrite an existing release.
if [[ -e "$SVN_DIR/tags/$VERSION" ]]; then
  die "Tag $VERSION already exists. Increment Version and Stable Tag before deploying again."
fi

# 4. Copy the production plugin files into trunk.
printf "Synchronizing plugin files into SVN trunk...\n"
rsync -a --delete \
  --exclude='.svn/' \
  --exclude='.git/' \
  --exclude='.github/' \
  --exclude='.DS_Store' \
  --exclude='node_modules/' \
  --exclude='.wordpress-org/' \
  --exclude='.env' \
  --exclude='.env.*' \
  --exclude='*.log' \
  --exclude='*.zip' \
  --exclude='deploy*.sh' \
  --exclude='deploy*.command' \
  "$PLUGIN_DIR/" "$SVN_DIR/trunk/"

# Optional WordPress.org page assets:
# Put banner/icon/screenshot files in PLUGIN_DIR/.wordpress-org/
if [[ -d "$PLUGIN_DIR/.wordpress-org" ]]; then
  printf "Synchronizing .wordpress-org files into SVN assets...\n"
  rsync -a --delete \
    --exclude='.svn/' \
    --exclude='.DS_Store' \
    "$PLUGIN_DIR/.wordpress-org/" "$SVN_DIR/assets/"
fi

# 5. Schedule additions and deletions.
svn add --force "$SVN_DIR/trunk" >/dev/null
if [[ -d "$PLUGIN_DIR/.wordpress-org" ]]; then
  svn add --force "$SVN_DIR/assets" >/dev/null
fi

while IFS= read -r missing; do
  [[ -n "$missing" ]] && svn rm --force "$missing" >/dev/null
done < <(svn status "$SVN_DIR" | sed -n 's/^!       //p')

# 6. Create the immutable release tag from the prepared trunk.
printf "Creating SVN tag %s...\n" "$VERSION"
svn copy "$SVN_DIR/trunk" "$SVN_DIR/tags/$VERSION"
svn add --force "$SVN_DIR/tags/$VERSION" >/dev/null

printf "\nFiles to commit:\n"
svn status "$SVN_DIR"
printf "\nCommitting release %s as WordPress.org user %s...\n" "$VERSION" "$SVN_USERNAME"

svn commit "$SVN_DIR" \
  --username "$SVN_USERNAME" \
  -m "Release ${VERSION}"

printf "\n=== Deployment committed successfully ===\n"
printf "Plugin page: %s\n" "$PUBLIC_URL"
printf "SVN tag:     %s/tags/%s\n" "$SVN_URL" "$VERSION"
printf "\nCheck your WordPress.org account email for any release-confirmation message.\n"
