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

# ===OBM-SCRIPT===
# title: Deploy a frontend project via rsync
# description: Syncs a frontend project through the deployment chain (arkon → vega staging → dwsrv production) with CMS-writable directories excluded.
# usage: obm-sync-project.sh [--dry-run] [--staging|--production] [--identity <file>] <project_name> [user@host[:port]]
# category: deploy
# arg: --dry-run       "Preview the sync without transferring"
# arg: --staging       "Force staging mode (overrides target detection)"
# arg: --production    "Force production mode (overrides target detection)"
# arg: --identity      "SSH private key for the target connection"
# arg: <project_name>  "Project directory under /var/www/projects"
# arg: <target_host>   "Target server (default: vega staging); accepts user@host[:port]"
# ===OBM-SCRIPT-END===

# ======================================================================
# obm-sync-project.sh — Deploy a frontend project using rsync
#                       with CMS-writable directory exclusion.
#
#   Deployment chain: arkon → vega (staging) → dwsrv (production)
#   Run this script on arkon to sync to vega, then on vega to sync to dwsrv.
#
# Usage: obm-sync-project.sh [--dry-run] [--staging|--production] <project_name> [user@host[:port]]
#
#   --dry-run, -n    Preview what would be synced (no actual transfer)
#   --staging        Force staging mode (overrides target detection)
#   --production     Force production mode (overrides target detection)
#   <project_name>   Project directory name under /var/www/projects
#   [target_host]    Optional — target server (default: 40.160.34.106, vega staging)
#                    Formats: IP, hostname, user@host, host:port, user@host:port
#
#   Examples:
#     obm-sync-project.sh --dry-run dylanwatts.de                       # preview to vega
#     obm-sync-project.sh dylanwatts.de                                 # sync to vega
#     obm-sync-project.sh dylanwatts.de root@144.76.168.72             # sync to dwsrv (production)
#     obm-sync-project.sh --staging dylanwatts.de root@10.99.0.2:2222  # sync to obm-staging
#     obm-sync-project.sh --dry-run dylanwatts.de root@10.99.0.2:2222  # preview to obm-staging
#
#   Excludes CMS/runtime write targets (cache/, dbase/, config/sets/*creds*,
#   backup-cms-articles/, media/documents/, media/bug-reports/, media/images/clients/,
#   media/videos/, media/reports/, temp/, .git/) so they survive untouched on the target.
#   config/sets/*creds* keeps the deprecated in-project credential files off every target
#   (credentials belong in /etc/openbam/ or the vault). media/images/ is synced (site images)
#   on PRODUCTION targets. On the staging target (vega) articles/, modules/,
#   config/sets/ AND media/images/ are additionally excluded because the CMS
#   backend edits them there via PHP-FPM as www-data (staging also authorizes
#   admin image uploads into media/images/); they are delivered to production by
#   the vega -> dwsrv deployment itself. Only config/sets/ (project.ini,
#   uris_*.ini — the CMS config editor write surface) is excluded; dev-authored
#   config subtrees such as config/tags/ (parser/translation tags) DO flow to
#   staging so the current multilingual tags stay in sync.
#
#   After sync, runs obm-project-permissions.sh on the target to fix ownership.
# ======================================================================

PROJECTS_ROOT="/var/www/projects"
DEFAULT_HOST="40.160.34.106"
DEFAULT_USER="debian"

usage() {
    echo "Usage: $0 [--dry-run] [--staging|--production] [--identity <file>] <project_name> [target_host]"
    echo ""
    echo "  Deploys a frontend project from this host to a target server"
    echo "  using rsync with CMS-writable directory exclusion."
    echo ""
    echo "  Arguments:"
    echo "    project_name   Project directory under /var/www/projects"
    echo "    target_host    Target server (default: 40.160.34.106, vega staging)"
    echo "                   Accepts IP, hostname, user@host, host:port, user@host:port"
    echo ""
    echo "  Options:"
    echo "    --dry-run, -n    Preview without transferring files"
    echo "    --staging        Force staging mode (overrides target detection)"
    echo "    --production     Force production mode (overrides target detection)"
    echo "    --identity FILE  SSH private key for the target (both rsync and the"
    echo "                     remote permissions call); useful when host and"
    echo "                     container share an IP but need different keys"
    echo ""
    echo "  Examples:"
    echo "    $0 --dry-run dylanwatts.de"
    echo "    $0 dylanwatts.de"
    echo "    $0 dylanwatts.de root@144.76.168.72"
    echo "    $0 --staging --identity ~/.ssh/obm-staging_deploy dylanwatts.de root@10.99.0.2:2222"
    exit 1
}

DRY_RUN=false
PROJECT=""
TARGET_HOST=""  # optional; falls back to STAGING_HOST below
FORCE_MODE=""   # "", "staging" or "production"
IDENTITY=""     # optional SSH private key for the target

while [[ $# -gt 0 ]]; do
    case "$1" in
        --dry-run|-n) DRY_RUN=true; shift ;;
        --staging)    FORCE_MODE="staging"; shift ;;
        --production) FORCE_MODE="production"; shift ;;
        --identity)   IDENTITY="${2:?--identity requires a file argument}"; shift 2 ;;
        -h|--help)    usage ;;
        *)
            if [[ -z "$PROJECT" ]]; then
                PROJECT="$1"
            elif [[ -z "$TARGET_HOST" ]]; then
                TARGET_HOST="$1"
            else
                echo "ERROR: Too many arguments: $1"
                usage
            fi
            shift
            ;;
    esac
done

if [[ -z "$PROJECT" ]]; then
    echo "ERROR: Project name is required."
    echo ""
    usage
fi

if [[ ! "$PROJECT" =~ ^[A-Za-z0-9._-]+$ ]]; then
    echo "ERROR: Invalid project name: $PROJECT"
    exit 1
fi

PROJECT_DIR="$PROJECTS_ROOT/$PROJECT"
if [[ ! -d "$PROJECT_DIR" ]]; then
    echo "ERROR: Project directory not found: $PROJECT_DIR"
    exit 1
fi

# --- Resolve target host, user and port --------------------------------
TARGET_HOST="${TARGET_HOST:-$DEFAULT_HOST}"

# Target formats: host | user@host | host:port | user@host:port
TARGET_PORT="22"
if [[ "$TARGET_HOST" == *@* ]]; then
    TARGET_USER="${TARGET_HOST%%@*}"
    TARGET_HOST="${TARGET_HOST#*@}"
else
    TARGET_USER="$DEFAULT_USER"
fi
if [[ "$TARGET_HOST" == *:* ]]; then
    TARGET_PORT="${TARGET_HOST##*:}"
    TARGET_HOST="${TARGET_HOST%%:*}"
fi
if [[ ! "$TARGET_PORT" =~ ^[0-9]+$ ]]; then
    echo "ERROR: Invalid port in target: $TARGET_PORT"
    exit 1
fi

# --- Detect staging target -------------------------------------------
# The staging server hosts the CMS backend, which edits articles/, modules/
# and config/sets/ directly through PHP-FPM as www-data. These CMS write
# targets must survive deployment, so they are excluded ONLY when the target
# is the staging host. On production they are delivered by the deployment.
# Dev-authored config subtrees (config/tags/, config/routes/) are NOT CMS
# write targets and flow on every target.
STAGING_HOST=""
STAGING_IP=""
STAGING_PORT=""
CONFIG="$PROJECT_DIR/config/sets/project.ini"
if [[ -f "$CONFIG" ]]; then
    STAGING_HOST=$(awk '
        /^\[servers\]/  { inservers = 1; next }
        /^\[/           { inservers = 0 }
        inservers && /^[[:space:]]*staging[[:space:]]*=/ {
            sub(/^[^=]*=[[:space:]]*/, "");
            gsub(/[",;]/, "");
            gsub(/^[[:space:]]+|[[:space:]]+$/, "");
            print; exit
        }' "$CONFIG")
    STAGING_IP=$(awk '
        /^\[servers\]/  { inservers = 1; next }
        /^\[/           { inservers = 0 }
        inservers && /^[[:space:]]*stagingIp[[:space:]]*=/ {
            sub(/^[^=]*=[[:space:]]*/, "");
            gsub(/[",;]/, "");
            gsub(/^[[:space:]]+|[[:space:]]+$/, "");
            print; exit
        }' "$CONFIG")
    STAGING_PORT=$(awk '
        /^\[servers\]/  { inservers = 1; next }
        /^\[/           { inservers = 0 }
        inservers && /^[[:space:]]*stagingPort[[:space:]]*=/ {
            sub(/^[^=]*=[[:space:]]*/, "");
            gsub(/[",;]/, "");
            gsub(/^[[:space:]]+|[[:space:]]+$/, "");
            print; exit
        }' "$CONFIG")
fi

IS_STAGING=false
if [[ -n "$STAGING_HOST" && "$TARGET_HOST" == "$STAGING_HOST" ]]; then
    IS_STAGING=true
elif [[ -n "$STAGING_IP" && "$TARGET_HOST" == "$STAGING_IP" ]]; then
    IS_STAGING=true
fi
# A staging host/IP match is only valid on the configured staging port; the
# production container (obm-live) may share the host IP but never the port.
if $IS_STAGING && [[ -n "$STAGING_PORT" && "$TARGET_PORT" != "$STAGING_PORT" ]]; then
    IS_STAGING=false
fi
# CLI overrides (--staging / --production) take precedence over detection.
if [[ "$FORCE_MODE" == "staging" ]]; then
    IS_STAGING=true
    echo "WARNING: --staging override active — staging excludes apply regardless of target detection."
elif [[ "$FORCE_MODE" == "production" ]]; then
    IS_STAGING=false
    echo "WARNING: --production override active — production excludes apply regardless of target detection."
fi

# --- Rsync excludes: CMS/runtime writable dirs + noise ----------------
# cache/, dbase/ and the media upload dirs (documents/, images/clients/,
# videos/, reports/) are excluded on EVERY target — they hold user-applied
# content that must survive on the target and never be overwritten by the
# source. media/images/ itself is synced because it holds site/deployment
# images. On the staging target, articles/, modules/, config/sets/ and
# media/images/ are additional CMS write targets owned by www-data and are
# excluded too so arkon never overwrites staging's CMS-edited content. Only
# config/sets/ is excluded from config/ — dev-authored config/tags/ (parser +
# multilingual translation tags) flows so staging stays in sync with arkon.
EXCLUDES=(
    --exclude='cache/'
    --exclude='dbase/'
    --exclude='config/sets/*creds*'
    --exclude='backup-cms-articles/'
    --exclude='media/documents/'
    --exclude='media/bug-reports/'
    --exclude='media/images/clients/'
    --exclude='media/videos/'
    --exclude='media/reports/'
    --exclude='temp/'
    --exclude='.git/'
    --exclude='*.log'
    --exclude='*.tar'
    --exclude='*.tar.gz'
    --exclude='.DS_Store'
)
if $IS_STAGING; then
    EXCLUDES+=(
        --exclude='articles/'
        --exclude='modules/'
        --exclude='config/sets/'
        --exclude='media/images/'
    )
fi

# --- Build rsync flags ------------------------------------------------
# Owner/group are NOT preserved from the source (--no-owner --no-group); the
# [2/2] obm-project-permissions.sh step normalizes ownership to the
# staging/production model on the target anyway.
# The remote rsync runs via sudo (--rsync-path) so the SSH user can write into
# target dirs owned by other users (e.g. the www-data-owned config/tags/ that
# must flow to staging). The SSH user has passwordless sudo; on production the
# target user is root. CMS write surfaces (articles/, modules/, config/sets/,
# media/images/ on staging) stay excluded and are never touched regardless.
# --- Build SSH/rsync connection options --------------------------------
SSH_OPTS=(-p "$TARGET_PORT")
if [[ -n "$IDENTITY" ]]; then
    SSH_OPTS+=(-i "$IDENTITY" -o IdentitiesOnly=yes)
fi

RSYNC_FLAGS=(-avz --delete --no-owner --no-group --rsync-path="sudo rsync" -e "ssh ${SSH_OPTS[*]}")
if $DRY_RUN; then
    RSYNC_FLAGS+=(-n)
fi

echo "============================================"
echo "Project Sync: $PROJECT"
if $DRY_RUN; then echo "Mode:      DRY RUN (no changes will be made)"; fi
echo "Started:   $(date '+%Y-%m-%d %H:%M:%S')"
echo "Source:    $PROJECT_DIR/"
echo "Target:    $TARGET_USER@$TARGET_HOST:$TARGET_PORT:$PROJECT_DIR/  ($(if $IS_STAGING; then echo staging; else echo production; fi))"
echo "Excluded:  cache/ dbase/ config/sets/*creds* backup-cms-articles/ media/documents/ media/bug-reports/ media/images/clients/ media/videos/ media/reports/ temp/ .git/$(if $IS_STAGING; then echo " articles/ modules/ config/sets/ media/images/"; fi)"
echo "============================================"
echo ""

# --- 1) Rsync source to target ----------------------------------------
echo "[1/2] Syncing files..."
rsync "${RSYNC_FLAGS[@]}" "${EXCLUDES[@]}" \
    "$PROJECT_DIR/" \
    "$TARGET_USER@$TARGET_HOST:$PROJECT_DIR/"

if $DRY_RUN; then
    echo ""
    echo "============================================"
    echo "DRY RUN COMPLETE — no files were transferred."
    echo "============================================"
    exit 0
fi

# --- 2) Fix permissions on target via local script --------------------
echo ""
echo "[2/2] Fixing permissions on target server..."
ssh "${SSH_OPTS[@]}" "$TARGET_USER@$TARGET_HOST" \
    "$PROJECTS_ROOT/../bin/bash/obm-project-permissions.sh $PROJECT"

echo ""
echo "============================================"
echo "SYNC COMPLETE"
echo "Finished: $(date '+%Y-%m-%d %H:%M:%S')"
echo "============================================"
