#!/bin/bash
# =============================================================================
# WOOO AIOps - MOMO Pro database backup into the 110 restic repository.
#
# 2026-05-07 ogt + Codex:
# - Bring the previously host-only /backup/scripts/backup-momo.sh under repo
#   control so Ansible can rebuild 110 without losing this backup domain.
# - Offsite upload is intentionally handled by sync-offsite-backups.sh; this
#   script only creates the local restic snapshot.
# - PostgreSQL credentials stay inside the 188 momo-db container environment.
# =============================================================================

set -euo pipefail

source "$(dirname "$0")/common.sh"

SERVICE="momo"
MOMO_HOST="${MOMO_HOST:-192.168.0.188}"
MOMO_SSH_USER="${MOMO_SSH_USER:-ollama}"
MOMO_DB_CONTAINER="${MOMO_DB_CONTAINER:-momo-db}"
LOCAL_REPO="${BACKUP_BASE}/momo"
DUMP_DIR="$(mktemp -d /tmp/momo-backup.XXXXXX)"
SSH_OPTS=(-o StrictHostKeyChecking=accept-new -o ConnectTimeout=10)

cleanup() {
    rm -rf "${DUMP_DIR}"
}

dump_momo_postgres() {
    ssh "${SSH_OPTS[@]}" "${MOMO_SSH_USER}@${MOMO_HOST}" \
        "docker exec ${MOMO_DB_CONTAINER} sh -eu -c 'PGPASSWORD=\"\${POSTGRES_PASSWORD:?POSTGRES_PASSWORD missing}\" exec pg_dump -U \"\${POSTGRES_USER:-momo}\" -d \"\${POSTGRES_DB:-momo_analytics}\" --no-password --no-owner --no-acl'"
}

main() {
    local start_time
    local timestamp
    local dump_file
    local tags
    local snapshot_id
    local duration

    start_time=$(date +%s)
    timestamp=$(date '+%Y%m%d_%H%M%S')
    dump_file="${DUMP_DIR}/momo_${timestamp}.sql"
    trap cleanup EXIT

    log_info "========== MOMO Pro local restic backup start =========="

    log_info "Dumping momo PostgreSQL from ${MOMO_HOST} without exposing credentials..."
    if dump_momo_postgres >"${dump_file}"; then
        if [ ! -s "${dump_file}" ]; then
            log_error "MOMO PostgreSQL dump is empty"
            notify_clawbot "failed" "${SERVICE}" "MOMO database dump is empty"
            exit 1
        fi
        log_success "PostgreSQL dump complete ($(du -h "${dump_file}" | cut -f1))"
    else
        log_error "MOMO PostgreSQL dump failed"
        notify_clawbot "failed" "${SERVICE}" "MOMO database dump failed"
        exit 1
    fi

    if [ ! -d "${LOCAL_REPO}/data" ]; then
        log_info "Initializing restic repository: ${LOCAL_REPO}"
        restic -r "${LOCAL_REPO}" init --password-file "${RESTIC_PASSWORD_FILE}"
    fi

    tags=$(build_tags "${SERVICE}")
    restic -r "${LOCAL_REPO}" backup "${dump_file}" \
        --password-file "${RESTIC_PASSWORD_FILE}" \
        ${tags}

    snapshot_id=$(restic -r "${LOCAL_REPO}" snapshots --latest 1 --json --password-file "${RESTIC_PASSWORD_FILE}" 2>/dev/null | grep -oP '"short_id":"\K[^"]+' | head -1 || true)
    log_success "Restic backup complete: ${snapshot_id:-unknown}"

    cleanup_old_backups "${LOCAL_REPO}"
    log_info "Offsite copy is handled by sync-offsite-backups.sh; no direct rclone sync here."

    duration=$(($(date +%s) - start_time))
    log_success "========== MOMO Pro local restic backup complete (${duration}s) =========="
    notify_clawbot "success" "${SERVICE}" "MOMO Pro backup complete" "${duration}"
}

main "$@"
