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

# ===OBM-SCRIPT===
# title: Deploy the OpenBAM framework into a container target
# description: Tarball deploy of /var/www/programs/OpenBAM into an Incus container (or any SSH target) accepting user@host[:port]. Mirrors obm-deploy-fw-vega.sh semantics: rename existing, extract with --no-same-owner, fix cache/dbase ownership, make ai/ world-readable, verify checksum, re-index Meilisearch.
# usage: obm-deploy-fw-container.sh <user@host[:port]> [--projects=a,b] [--dry-run]
# category: deploy
# arg: <user@host[:port]>  "Target container endpoint (e.g. root@10.99.0.2:2222 or root@obm-live)"
# arg: --projects=         "Comma-separated projects to re-index (default dylanwatts.de)"
# arg: --dry-run           "Build the tarball and print the plan without transferring"
# ===OBM-SCRIPT-END===

# ======================================================================
# obm-deploy-fw-container.sh — Deploy the OpenBAM framework to a
#                              container target over SSH.
#
#   Usage: obm-deploy-fw-container.sh <user@host[:port]> [--projects=a,b]
#
#   Examples:
#     obm-deploy-fw-container.sh root@10.99.0.2:2222          # arkon -> obm-staging
#     obm-deploy-fw-container.sh root@obm-live                # obm-staging -> obm-live (bridge)
#
#   Steps:
#     1) rename the existing local tarball to OpenBAM_<ts>.tar.gz
#     2) create OpenBAM.tar.gz (--exclude='.git' --exclude='_tests')
#     3) scp to the target (port-aware)
#     4) rename + extract the live framework dir, fix cache/dbase ownership,
#        make ai/ world-readable, prune old backups when the helper exists
#     5) verify checksum on both sides
#     6) re-index the CMS search index for --projects
# ======================================================================

FRAMEWORK_ROOT="/var/www/programs/OpenBAM"
STORE_DIR="/var/www/programs"
BACKUP_DIR="/var/www/programs/backups"
ARCHIVE_NAME="OpenBAM"
ARCHIVE_FILE="${ARCHIVE_NAME}.tar.gz"
TIMESTAMP=$(date '+%Y%m%d-%H%M%S')
PROJECTS_TO_INDEX="dylanwatts.de"
TARGET=""
DRY_RUN=false
IDENTITY=""   # optional SSH private key for the target

usage() {
    echo "Usage: $0 <user@host[:port]> [--projects=a,b] [--identity <file>] [--dry-run]"
    echo ""
    echo "  Deploys the OpenBAM framework from this host into a container target."
    echo ""
    echo "  Arguments:"
    echo "    user@host[:port]   Target endpoint; user defaults to root, port to 22"
    echo "    --projects=a,b     Projects to re-index (default: dylanwatts.de)"
    echo "    --identity FILE    SSH private key for the target connection"
    echo "    --dry-run          Build + checksum the tarball, skip transfer/deploy"
    exit 1
}

while [[ $# -gt 0 ]]; do
    case "$1" in
        --projects=*) PROJECTS_TO_INDEX="${1#*=}"; shift ;;
        --identity)   IDENTITY="${2:?--identity requires a file argument}"; shift 2 ;;
        --dry-run)    DRY_RUN=true; shift ;;
        -h|--help)    usage ;;
        -*)           echo "ERROR: Unknown option: $1"; usage ;;
        *)
            if [[ -z "$TARGET" ]]; then TARGET="$1"; else echo "ERROR: Unexpected argument: $1"; usage; fi
            shift
            ;;
    esac
done

[[ -n "$TARGET" ]] || usage

# --- Split user@host:port ---------------------------------------------
if [[ "$TARGET" == *@* ]]; then
    TARGET_USER="${TARGET%%@*}"
    TARGET_REST="${TARGET#*@}"
else
    TARGET_USER="root"
    TARGET_REST="$TARGET"
fi
if [[ "$TARGET_REST" == *:* ]]; then
    TARGET_HOST="${TARGET_REST%%:*}"
    TARGET_PORT="${TARGET_REST##*:}"
else
    TARGET_HOST="$TARGET_REST"
    TARGET_PORT="22"
fi

SSH_OPTS=(-p "$TARGET_PORT")
SCP_OPTS=(-P "$TARGET_PORT")
if [[ -n "$IDENTITY" ]]; then
    SSH_OPTS+=(-i "$IDENTITY" -o IdentitiesOnly=yes)
    SCP_OPTS+=(-i "$IDENTITY" -o IdentitiesOnly=yes)
fi
SSH=(ssh "${SSH_OPTS[@]}" "$TARGET_USER@$TARGET_HOST")
SCP=(scp "${SCP_OPTS[@]}")

echo "============================================"
echo "OpenBAM Framework Deployment (container target)"
echo "Started: $(date '+%Y-%m-%d %H:%M:%S')"
echo "Target:  $TARGET_USER@$TARGET_HOST:$TARGET_PORT:$STORE_DIR/"
echo "Index:   $PROJECTS_TO_INDEX"
if $DRY_RUN; then echo "Mode:    DRY RUN"; fi
echo "============================================"
echo ""

# 1) Verify source exists
if [[ ! -d "$FRAMEWORK_ROOT" ]]; then
    echo "ERROR: Framework directory not found: $FRAMEWORK_ROOT"
    exit 1
fi

# 2) Rename existing archive if present
if [[ -f "$STORE_DIR/$ARCHIVE_FILE" ]]; then
    backup_name="${ARCHIVE_NAME}_${TIMESTAMP}.tar.gz"
    echo "[1/6] Renaming existing archive: $ARCHIVE_FILE -> $backup_name"
    mv "$STORE_DIR/$ARCHIVE_FILE" "$STORE_DIR/$backup_name"
else
    echo "[1/6] No existing archive to rename"
fi

# 3) Create tarball
echo "[2/6] Creating tarball archive (this may take a moment)..."
tar czf "$STORE_DIR/$ARCHIVE_FILE" \
    --exclude='.git' \
    --exclude='_tests' \
    -C "$(dirname "$FRAMEWORK_ROOT")" \
    "$(basename "$FRAMEWORK_ROOT")"

CHECKSUM=$(sha256sum "$STORE_DIR/$ARCHIVE_FILE" | cut -d' ' -f1)
archive_size=$(du -h "$STORE_DIR/$ARCHIVE_FILE" | cut -f1)
echo "       Archive: $STORE_DIR/$ARCHIVE_FILE ($archive_size)"
echo "       SHA256:  $CHECKSUM"

if $DRY_RUN; then
    echo ""
    echo "DRY RUN — tarball built and checksummed; skipping transfer and deploy."
    exit 0
fi

# 4) Copy to target
echo "[3/6] Copying archive to $TARGET_HOST..."
"${SCP[@]}" "$STORE_DIR/$ARCHIVE_FILE" "$TARGET_USER@$TARGET_HOST:$STORE_DIR/"

# 5) Deploy on the target
echo "[4/6] Deploying on the target..."
"${SSH[@]}" "
    set -euo pipefail
    cd '$STORE_DIR'

    # Verify the transferred archive
    echo '       Verifying checksum...'
    echo '$CHECKSUM  $ARCHIVE_FILE' | sha256sum -c - >/dev/null

    mkdir -p '$BACKUP_DIR'

    if [[ -d '$ARCHIVE_NAME' ]]; then
        backup_dir='${ARCHIVE_NAME}_${TIMESTAMP}'
        echo \"       Renaming existing: $ARCHIVE_NAME -> $BACKUP_DIR/\$backup_dir\"
        mv '$ARCHIVE_NAME' \"$BACKUP_DIR/\$backup_dir\"
    fi

    echo '       Extracting archive...'
    tar xzf '$ARCHIVE_FILE' --no-same-owner

    echo '       Fixing cache/dbase ownership...'
    find '$ARCHIVE_NAME' -maxdepth 3 -type d \( -name cache -o -name dbase \) \
        -exec chown -R www-data:www-data {} \; 2>/dev/null || true

    [[ -d '$ARCHIVE_NAME/ai' ]] && chmod -R a+rX '$ARCHIVE_NAME/ai' 2>/dev/null || true

    if [[ -x /var/www/bin/bash/obm-prune-fw-backups.sh ]]; then
        echo '       Pruning old backups...'
        /var/www/bin/bash/obm-prune-fw-backups.sh || true
    fi

    echo '       Framework deployed successfully.'
"

# 6) Re-index the CMS search index (Meilisearch) if available
echo "[5/6] Re-indexing CMS search index on target..."
"${SSH[@]}" "
    set -u
    CLI='/var/www/programs/OpenBAM/bin/cli-search-index'
    for project in $(echo "$PROJECTS_TO_INDEX" | tr ',' ' '); do
        if [[ ! -x \"\$CLI\" ]]; then
            echo \"       Search index CLI not present — skipping re-index for \$project\"
            continue
        fi
        if ! \"\$CLI\" --project=\"\$project\" --health > /dev/null 2>&1; then
            echo \"       Meilisearch not reachable — skipping re-index for \$project\"
            continue
        fi
        echo \"       Re-indexing search index for: \$project\"
        if \"\$CLI\" --project=\"\$project\" --reindex > /tmp/cli-search-index-\$project.log 2>&1; then
            tail -3 /tmp/cli-search-index-\$project.log
        else
            echo \"       WARNING: Re-index failed for \$project — see /tmp/cli-search-index-\$project.log\" >&2
            echo \"       Re-run manually: \$CLI --project=\$project --reindex\" >&2
        fi
    done
"

echo "[6/6] Verifying remote deployment..."
"${SSH[@]}" "test -x '$STORE_DIR/$ARCHIVE_NAME/bin/cli-search-index' && echo '       Remote framework OK' || echo '       WARNING: remote framework entry point missing'"

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