#!/usr/bin/env bash
# ============================================================================
# push-to-dev.sh
# Push the CURRENT mosiah brentwooddev site (database + wp-content) to the
# dev.brentwood.ca droplet. Runnable by any brentwooddev-dev member (rian, adi)
# and by Claude. Needs NO docker on mosiah (dumps the DB over the network).
#
#   Usage:  push-brentwood-dev          (if the /usr/local/bin symlink exists)
#       or:  bash /srv/apps/brentwooddev/deploy/push-to-dev.sh
#
# WHAT IT DOES (mosiah is the source of truth):
#   1. mysqldump brentwooddev from the shared MariaDB
#   2. import it into the droplet's database (replaces tables)
#   3. rewrite URLs brentwooddev.demoing.info -> dev.brentwood.ca + flush rewrites
#      (done BEFORE the media sync so the site isn't pointing at the old domain
#       for the duration of the rsync)
#   4. rsync wp-content to the droplet (incremental, --delete), EXCLUDING backup
#      and cache cruft (UpdraftPlus etc.) that must never be deployed
#
# NOTE: this OVERWRITES the droplet's dev site with mosiah's state. The droplet
#       is a deploy target, not a place to edit directly.
# ============================================================================
set -euo pipefail

# --- config -----------------------------------------------------------------
SRC=/srv/apps/brentwooddev
DEPLOY="$(cd "$(dirname "$(readlink -f "$0")")" && pwd)"   # readlink -f: resolve through the /usr/local/bin symlink
DROPLET=68.183.201.76          # dev-wp primary IP (Reserved IP 159.203.50.215 also points here)
DAPP=/opt/brentwood-wp         # stack dir on the droplet
SRC_URL=brentwooddev.demoing.info
DST_URL=dev.brentwood.ca

# --- single-runner lock -----------------------------------------------------
# Shared, group-writable lock in the deploy dir so it works for ANY
# brentwooddev-dev member (rian, adi, Claude). A per-user /tmp lock was avoided
# on purpose: it wouldn't stop two different users pushing to the droplet at once.
exec 9>"$DEPLOY/.push.lock"
flock -n 9 || { echo "ERROR: another push is already running."; exit 1; }

# --- ssh needs a 600 key; the shared deploy_key is group-readable, so copy it
#     to a private per-user temp file for this run -----------------------------
umask 077
TMPKEY=$(mktemp /tmp/.bwdeploy-XXXXXX)
TMPSQL=$(mktemp /tmp/.bwdev-XXXXXX.sql)
cleanup(){ rm -f "$TMPKEY" "$TMPSQL"; }
trap cleanup EXIT
cp "$DEPLOY/deploy_key" "$TMPKEY"; chmod 600 "$TMPKEY"
SSH="ssh -i $TMPKEY -o StrictHostKeyChecking=accept-new -o ConnectTimeout=15"

echo "==> [1/4] Dumping brentwooddev DB from shared MariaDB (network, no docker)..."
set -a; . "$SRC/.env"; set +a
MYSQL_PWD="$DB_PASSWORD" mysqldump --single-transaction --quick --no-tablespaces \
  --default-character-set=utf8mb4 -h 127.0.0.1 -P 3306 \
  -u"$DB_USER" "$DB_NAME" > "$TMPSQL"
  # NB: .env DB_HOST is 'host.containers.internal' (for containers); from the
  # mosiah host the shared MariaDB is reached at 127.0.0.1:3306.
unset DB_PASSWORD
echo "    dump size: $(du -h "$TMPSQL" | cut -f1)"

echo "==> [2/4] Importing DB into droplet..."
$SSH root@"$DROPLET" \
  'set -a; . '"$DAPP"'/.env; set +a; docker exec -i -e MYSQL_PWD="$DB_ROOT_PASSWORD" brentwood-wp-db-1 mariadb -uroot "$DB_NAME"' \
  < "$TMPSQL"

echo "==> [3/4] Rewriting URLs + flushing rewrites (before media sync)..."
$SSH root@"$DROPLET" '
  cd '"$DAPP"'
  WP=$(docker compose ps -q wordpress)
  docker exec "$WP" wp --allow-root --path=/var/www/html search-replace "'"$SRC_URL"'" "'"$DST_URL"'" --all-tables --skip-columns=guid --quiet
  docker exec "$WP" wp --allow-root option update siteurl "https://'"$DST_URL"'" >/dev/null
  docker exec "$WP" wp --allow-root option update home    "https://'"$DST_URL"'" >/dev/null
  docker exec "$WP" wp --allow-root rewrite flush --hard >/dev/null 2>&1 || true
'

echo "==> [4/4] Syncing wp-content (incremental; excludes backups/cache cruft)..."
rsync -a --delete \
  --exclude="/updraft/" --exclude="/ai1wm-backups/" --exclude="/backups/" \
  --exclude="/cache/" --exclude="/upgrade/" --exclude="*.log" \
  -e "$SSH" "$SRC/wp-content/" root@"$DROPLET":"$DAPP/wp-content/"
$SSH root@"$DROPLET" 'chown -R 33:33 '"$DAPP"'/wp-content'

echo "==> DONE — https://$DST_URL updated from mosiah (still behind the access gate)."
