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

# Stonks Oracle — Redis State Backup
# Triggers a Redis BGSAVE and copies the RDB dump file locally.
# Useful before major deployments or database resets.
#
# Usage:
#   ./scripts/backup-redis.sh
#
# Requires: kubectl access to the cluster

NAMESPACE_REDIS="redis-service"
REDIS_POD="redis-master-0"
REDIS_PASSWORD="${REDIS_PASSWORD:-PSCh4ng3me!}"

BACKUP_DIR="${BACKUP_DIR:-$HOME/backups/stonks-oracle}"
TIMESTAMP=$(date +%Y%m%d-%H%M%S)
BACKUP_FILE="redis-${TIMESTAMP}.rdb"
BACKUP_PATH="${BACKUP_DIR}/${BACKUP_FILE}"

echo "=== Stonks Oracle Redis Backup ==="
echo "Timestamp: ${TIMESTAMP}"

mkdir -p "${BACKUP_DIR}"

# Trigger BGSAVE
echo "[1/3] Triggering Redis BGSAVE..."
kubectl exec -n "${NAMESPACE_REDIS}" "${REDIS_POD}" -- \
  redis-cli -a "${REDIS_PASSWORD}" BGSAVE 2>/dev/null

# Wait for save to complete
echo "       Waiting for background save..."
sleep 5

LAST_SAVE=$(kubectl exec -n "${NAMESPACE_REDIS}" "${REDIS_POD}" -- \
  redis-cli -a "${REDIS_PASSWORD}" LASTSAVE 2>/dev/null)
echo "       Last save timestamp: ${LAST_SAVE}"

# Copy the RDB file
echo "[2/3] Copying RDB dump..."
kubectl cp "${NAMESPACE_REDIS}/${REDIS_POD}:/data/dump.rdb" "${BACKUP_PATH}" 2>/dev/null || \
  echo "WARNING: Could not copy RDB file (path may differ)"

if [ -f "${BACKUP_PATH}" ]; then
  BACKUP_SIZE=$(du -h "${BACKUP_PATH}" | cut -f1)
  echo "       Size: ${BACKUP_SIZE}"
else
  echo "       RDB copy failed — checking alternative paths..."
  # Try common Redis data paths
  for path in /data/dump.rdb /var/lib/redis/dump.rdb /bitnami/redis/data/dump.rdb; do
    kubectl cp "${NAMESPACE_REDIS}/${REDIS_POD}:${path}" "${BACKUP_PATH}" 2>/dev/null && break
  done
  if [ -f "${BACKUP_PATH}" ]; then
    BACKUP_SIZE=$(du -h "${BACKUP_PATH}" | cut -f1)
    echo "       Size: ${BACKUP_SIZE}"
  else
    echo "WARNING: Could not locate RDB dump file"
  fi
fi

# Show key stats
echo "[3/3] Redis key stats..."
kubectl exec -n "${NAMESPACE_REDIS}" "${REDIS_POD}" -- \
  redis-cli -a "${REDIS_PASSWORD}" INFO keyspace 2>/dev/null | grep "^db"

echo ""
echo "=== Redis backup complete ==="
echo "File: ${BACKUP_PATH}"
