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

script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$script_dir/lib/common.sh"
source "$script_dir/lib/manifest.sh"
source "$script_dir/lib/postgres.sh"
source "$script_dir/lib/clickhouse.sh"
source "$script_dir/lib/config.sh"
source "$script_dir/lib/report.sh"

repo_root="$(backup_repo_root)"
services="$(normalize_service_filter "${DUMP_SERVICES:-all}")"
mode="${DUMP_MODE:-maintenance}"
backup_root="${BACKUP_ROOT:-$repo_root/backups}"
backup_dir="${BACKUP:-$backup_root/baron-sso-backup-$(backup_timestamp)}"

mkdir -p "$backup_dir/reports"
create_manifest "$backup_dir" "$mode" "$services"
service_timings_json="[]"

run_backup_step() {
  local service="$1"
  shift

  local started_at
  local finished_at
  local duration_seconds

  started_at="$(date +%s)"
  "$@"
  finished_at="$(date +%s)"
  duration_seconds="$((finished_at - started_at))"
  service_timings_json="$(jq -c \
    --arg service "$service" \
    --argjson duration "$duration_seconds" \
    '. + [{service:$service, duration_seconds:$duration}]' \
    <<<"$service_timings_json")"
}

backup_log "Creating backup at $backup_dir"
backup_log "Backup mode: $mode"
backup_log "Services: $services"

if service_enabled postgres "$services"; then
  run_backup_step postgres dump_baron_postgres "$backup_dir"
fi

if service_enabled ory-postgres "$services"; then
  run_backup_step ory-postgres dump_ory_postgres "$backup_dir"
fi

if service_enabled clickhouse "$services"; then
  run_backup_step clickhouse dump_baron_clickhouse "$backup_dir"
fi

if service_enabled ory-clickhouse "$services"; then
  run_backup_step ory-clickhouse dump_ory_clickhouse "$backup_dir"
fi

if service_enabled config "$services"; then
  run_backup_step config dump_config_snapshot "$backup_dir"
fi

write_backup_markdown_report "$backup_dir" "succeeded" "$services" "$service_timings_json"
backup_checksum_file "$backup_dir"
BACKUP="$backup_dir" "$script_dir/verify-dump.sh"

backup_log "Backup complete: $backup_dir"
