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

# Required env vars:
#   FLYNN_DATA_DIR (default: ~/.local/share/flynn)
#   FLYNN_BACKUP_DIR (default: ~/.local/share/flynn/backups)
#   MINIO_ENDPOINT
#   MINIO_ACCESS_KEY
#   MINIO_SECRET_KEY
#   MINIO_BUCKET
#
# Optional:
#   MINIO_PREFIX (default: flynn)
#   MINIO_SECURE (default: true)

DATA_DIR="${FLYNN_DATA_DIR:-$HOME/.local/share/flynn}"
BACKUP_DIR="${FLYNN_BACKUP_DIR:-$HOME/.local/share/flynn/backups}"
MINIO_PREFIX="${MINIO_PREFIX:-flynn}"
MINIO_SECURE="${MINIO_SECURE:-true}"

if [[ -z "${MINIO_ENDPOINT:-}" || -z "${MINIO_ACCESS_KEY:-}" || -z "${MINIO_SECRET_KEY:-}" || -z "${MINIO_BUCKET:-}" ]]; then
  echo "Missing MinIO config. Set MINIO_ENDPOINT, MINIO_ACCESS_KEY, MINIO_SECRET_KEY, MINIO_BUCKET." >&2
  exit 1
fi

if ! command -v mc >/dev/null 2>&1; then
  echo "MinIO client (mc) not found in PATH." >&2
  exit 1
fi

mkdir -p "${BACKUP_DIR}"

STAMP="$(date -u +%Y%m%d_%H%M%S)"
ARCHIVE="flynn_${STAMP}.tar.gz"
ARCHIVE_PATH="${BACKUP_DIR}/${ARCHIVE}"

ENTRIES=()
[[ -f "${DATA_DIR}/sessions.db" ]] && ENTRIES+=("sessions.db")
[[ -f "${DATA_DIR}/vectors.db" ]] && ENTRIES+=("vectors.db")
[[ -d "${DATA_DIR}/memory" ]] && ENTRIES+=("memory")

if [[ ${#ENTRIES[@]} -eq 0 ]]; then
  echo "No backup inputs found under ${DATA_DIR}" >&2
  exit 1
fi

tar -czf "${ARCHIVE_PATH}" -C "${DATA_DIR}" "${ENTRIES[@]}"

if [[ "${MINIO_SECURE}" == "true" ]]; then
  PROTO="https"
else
  PROTO="http"
fi

export MC_HOST_flynnbackup="${PROTO}://${MINIO_ACCESS_KEY}:${MINIO_SECRET_KEY}@${MINIO_ENDPOINT}"
mc mb --ignore-existing "flynnbackup/${MINIO_BUCKET}" >/dev/null
mc cp "${ARCHIVE_PATH}" "flynnbackup/${MINIO_BUCKET}/${MINIO_PREFIX}/${ARCHIVE}" >/dev/null

echo "Backup created: ${ARCHIVE_PATH}"
echo "Uploaded to: flynnbackup/${MINIO_BUCKET}/${MINIO_PREFIX}/${ARCHIVE}"
