#!/usr/bin/env bash
#
# Pushes one page (a post, or any Canvas page) from local DDEV to production,
# with its media, files and terms. Content never goes into git.
#
#   scripts/deploy/push-content.sh /blog/my-post        (asks before pushing)
#   scripts/deploy/push-content.sh /blog/my-post -y     (no question)
#
# 1. ddev drush marcus:content-export -> .content-push/<time>/ (gitignored)
# 2. backs up the production database (backups/<time>-content/db.sql.gz)
# 3. rsyncs the export to the server
# 4. drush marcus:content-import there: new content is created, existing
#    content (same UUID) is updated; user accounts are never touched
#
# The local copy wins: pushing a page overwrites edits made to it on
# production. Server details come from .deploy.env (copy .deploy.env.example).

set -euo pipefail

PAGE="${1:?usage: push-content.sh <path, e.g. /blog/my-post> [-y]}"
YES="${2:-}"
ROOT="$(cd "$(dirname "$0")/../.." && pwd)"

if [ -f "$ROOT/.deploy.env" ]; then
  # shellcheck disable=SC1091
  . "$ROOT/.deploy.env"
fi
: "${DEPLOY_HOST:?Set DEPLOY_HOST in .deploy.env}"
: "${DEPLOY_USER:?Set DEPLOY_USER in .deploy.env}"
DEPLOY_PATH="${DEPLOY_PATH:-/var/www/marcus-blog}"
SSH_PORT="${DEPLOY_SSH_PORT:-22}"
SSH=(ssh -p "$SSH_PORT")
[ -n "${DEPLOY_SSH_KEY_FILE:-}" ] && SSH+=(-i "$DEPLOY_SSH_KEY_FILE")
TARGET="$DEPLOY_USER@$DEPLOY_HOST"

STAMP="$(date +%Y%m%d-%H%M%S)"
LOCAL_DIR="$ROOT/.content-push/$STAMP"
REMOTE_DIR="$DEPLOY_PATH/incoming/content-$STAMP"
trap 'rm -rf "$LOCAL_DIR"' EXIT

echo "==> Exporting $PAGE"
(cd "$ROOT" && ddev drush marcus:content-export "$PAGE" --dir="/var/www/html/.content-push/$STAMP")
echo "    $(find "$LOCAL_DIR" -name '*.yml' | wc -l) entities, $(du -sh "$LOCAL_DIR" | cut -f1)"
find "$LOCAL_DIR" -name '*.yml' -printf '    %P\n' | sort

if [ "$YES" != "-y" ]; then
  read -r -p "Push this to $DEPLOY_HOST? [y/N] " answer
  [ "$answer" = "y" ] || [ "$answer" = "Y" ] || { echo "Cancelled."; exit 0; }
fi

# Runs a command on the server in the live release with the production env.
remote() {
  "${SSH[@]}" "$TARGET" bash -s -- "$DEPLOY_PATH" "$@" <<'REMOTE'
set -euo pipefail
DEPLOY_PATH="$1"; shift
set -a; . "$DEPLOY_PATH/shared/.env"; set +a
# Drush builds absolute URLs (llms.txt, the sitemap) from the public URL.
[ -n "${SITE_URL:-}" ] && export DRUSH_OPTIONS_URI="${DRUSH_OPTIONS_URI:-$SITE_URL}"
cd "$DEPLOY_PATH/current"
"$@"
REMOTE
}

echo "==> Backing up the production database"
remote mkdir -p "$DEPLOY_PATH/backups/$STAMP-content"
remote vendor/bin/drush sql:dump --gzip --extra-dump=--no-tablespaces --result-file="$DEPLOY_PATH/backups/$STAMP-content/db.sql"

echo "==> Uploading"
rsync -az --mkpath -e "${SSH[*]}" "$LOCAL_DIR/" "$TARGET:$REMOTE_DIR/"

echo "==> Importing"
remote vendor/bin/drush marcus:content-import "$REMOTE_DIR"
remote vendor/bin/drush cache:rebuild
remote vendor/bin/drush simple-sitemap:generate
remote rm -rf "$REMOTE_DIR"

echo "==> Done. Database backup: $DEPLOY_PATH/backups/$STAMP-content/db.sql.gz"
