#!/bin/bash

# Edge Backup Script
# Runs extract-db-password, extracts mongo TLS certs, discovers primary mongo pod, then runs local mongodump (TLS) for a cluster.

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
UTIL_DIR="${SCRIPT_DIR}/util"
KUBECONFIG_FILE=""
BACKUP_DIR=""

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

log_info() { echo -e "${BLUE}[INFO]${NC} $1"; }
log_success() { echo -e "${GREEN}[SUCCESS]${NC} $1"; }
log_warning() { echo -e "${YELLOW}[WARNING]${NC} $1"; }
log_error() { echo -e "${RED}[ERROR]${NC} $1"; }

show_help() {
    cat << EOF
Edge Backup Script

Runs for a given kubeconfig:
  1. Extract and clean secrets to <backup-dir>/cleaned-secrets
  2. Extract DB password (configserversecret in hubble-system)
  3. Extract MongoDB TLS certificates to <backup-dir>/mongo-tls
  4. Discover MongoDB primary pod (get-mongo-primary-pod.sh)
  5. Run mongodump-local-tls.sh (port-forward, local mongodump with TLS, verify output)

Usage: $0 [OPTIONS]

OPTIONS:
    --kubeconfig FILE    Path to kubeconfig file (REQUIRED)
    --backup-dir DIR     Backup directory/folder name (default: mongo_hubble_backup_<timestamp>)
    --help               Show this help message

EXAMPLES:
    $0 --kubeconfig /path/to/kubeconfig
    $0 --kubeconfig /path/to/kubeconfig --backup-dir /path/to/backup_dir

EOF
}

parse_arguments() {
    while [[ $# -gt 0 ]]; do
        case $1 in
            --kubeconfig)
                KUBECONFIG_FILE="$2"
                shift 2
                ;;
            --backup-dir)
                BACKUP_DIR="$2"
                shift 2
                ;;
            --help)
                show_help
                exit 0
                ;;
            *)
                log_error "Unknown option: $1"
                show_help
                exit 1
                ;;
        esac
    done
}

main() {
    parse_arguments "$@"

    if [[ -z "$KUBECONFIG_FILE" ]]; then
        log_error "Kubeconfig path is required (--kubeconfig FILE)"
        show_help
        exit 1
    fi
    if [[ ! -f "$KUBECONFIG_FILE" ]]; then
        log_error "Kubeconfig file not found: $KUBECONFIG_FILE"
        exit 1
    fi

    for script in extract-and-clean-secrets.sh extract-db-password.sh extract-mongo-tls-certs.sh get-mongo-primary-pod.sh mongodump-local-tls.sh; do
        if [[ ! -x "${UTIL_DIR}/${script}" ]]; then
            log_error "Required script not found or not executable: ${UTIL_DIR}/${script}"
            exit 1
        fi
    done

    if ! which mongodump >/dev/null 2>&1; then
        log_error "mongodump binary not found in PATH. Please install mongo database tools or add mongodump to PATH."
        exit 1
    fi

    if [[ -z "$BACKUP_DIR" ]]; then
        BACKUP_DIR="mongo_hubble_backup_$(date +%Y%m%d-%H%M%S)"
    fi

    # Ensure backup dir exists so we can put cleaned-secrets inside it
    mkdir -p "$BACKUP_DIR"

    export KUBECONFIG="$KUBECONFIG_FILE"

    # 1. Extract and clean secrets into backup-dir/cleaned-secrets
    log_info "Step 1: Extracting and cleaning secrets to ${BACKUP_DIR}/cleaned-secrets..."
    if ! "${UTIL_DIR}/extract-and-clean-secrets.sh" --kubeconfig "$KUBECONFIG_FILE" --output-dir "${BACKUP_DIR}/cleaned-secrets"; then
        log_error "extract-and-clean-secrets.sh failed"
        exit 1
    fi
    log_success "Secrets extracted and cleaned"

    # 2. Extract DB password (last line of stdout is the password)
    log_info "Step 2: Extracting DB password from cluster..."
    PASSWORD=$("${UTIL_DIR}/extract-db-password.sh" --kubeconfig "$KUBECONFIG_FILE" 2>/dev/null | tail -1)
    if [[ -z "$PASSWORD" ]]; then
        log_error "Failed to extract DB password"
        exit 1
    fi
    log_success "DB password extracted"

    # 3. Extract MongoDB TLS certificates
    log_info "Step 3: Extracting MongoDB TLS certificates to ${BACKUP_DIR}/mongo-tls..."
    TLS_CERTS_AVAILABLE=true
    if ! "${UTIL_DIR}/extract-mongo-tls-certs.sh" --kubeconfig "$KUBECONFIG_FILE" --output-dir "${BACKUP_DIR}/mongo-tls"; then
        log_warning "extract-mongo-tls-certs.sh failed; proceeding without TLS certificates"
        TLS_CERTS_AVAILABLE=false
    else
        log_success "MongoDB TLS certificates extracted"
    fi

    # 4. Discover MongoDB primary pod
    log_info "Step 4: Discovering MongoDB primary pod..."
    if [[ "$TLS_CERTS_AVAILABLE" == "true" ]]; then
        POD_NUMBER=$("${UTIL_DIR}/get-mongo-primary-pod.sh" -p "$PASSWORD" -k "$KUBECONFIG_FILE" --tls)
    else
        POD_NUMBER=$("${UTIL_DIR}/get-mongo-primary-pod.sh" -p "$PASSWORD" -k "$KUBECONFIG_FILE")
    fi
    if [[ -z "$POD_NUMBER" ]]; then
        log_error "Failed to get MongoDB primary pod number"
        exit 1
    fi
    log_success "MongoDB primary is mongo-${POD_NUMBER}"

    # 5. Run local mongodump via port-forward, verify output in backup dir
    log_info "Step 5: Running mongodump-local-tls (port-forward, verify, write to ${BACKUP_DIR})..."
    mongodump_args=(
        -p "$PASSWORD"
        -l "$BACKUP_DIR"
        -k "$KUBECONFIG_FILE"
        -N "$POD_NUMBER"
    )
    if [[ "$TLS_CERTS_AVAILABLE" == "true" ]]; then
        mongodump_args+=(--tls-dir "${BACKUP_DIR}/mongo-tls")
    fi
    if ! "${UTIL_DIR}/mongodump-local-tls.sh" "${mongodump_args[@]}"; then
        log_error "mongodump-local-tls.sh failed"
        exit 1
    fi
    log_success "MongoDB dump completed and verified in $BACKUP_DIR"

    # 6. Write backup summary
    log_info "Step 6: Writing backup summary..."
    local DATABASES=(hubbledb hubble_timeseriesdb hubble_archivedb)
    local summary_file="${BACKUP_DIR}/backup_summary.txt"
    {
        echo "MongoDB Edge Backup Summary (mongodump-local-tls)"
        echo "==============================================="
        echo "Backup Date: $(date)"
        echo "Backup Directory: $BACKUP_DIR"
        echo "Primary Pod: mongo-${POD_NUMBER}"
        echo ""
        echo "Databases:"
        for db in "${DATABASES[@]}"; do
            local db_dir="${BACKUP_DIR}/${db}"
            if [[ -d "$db_dir" ]]; then
                local size=$(du -sh "$db_dir" 2>/dev/null | cut -f1)
                echo "  - $db: $size"
            else
                echo "  - $db: (missing)"
            fi
        done
    } > "$summary_file"
    log_success "Backup summary created: $summary_file"

    log_success "Edge backup completed successfully. Backup directory: $BACKUP_DIR"
}

main "$@"
