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

APP_NAME="vaultwarden"
BASE_DIR="$(cd "$(dirname "$0")" && pwd)"
BACKUP_DIR="$BASE_DIR/backup"
TIMESTAMP=$(date +%Y%m%d-%H%M)

echo "📦 備份 $APP_NAME..."

mkdir -p "$BACKUP_DIR"

POD=$(kubectl get pod -l "app=$APP_NAME" -o jsonpath="{.items[0].metadata.name}")

if [ -z "$POD" ]; then
    echo "❌ 找不到 $APP_NAME 的 Pod"
    exit 1
fi

echo "備份資料..."
kubectl exec $POD -- tar czf /tmp/backup.tar.gz /data
kubectl cp $POD:/tmp/backup.tar.gz "$BACKUP_DIR/$APP_NAME-$TIMESTAMP.tar.gz"
kubectl exec $POD -- rm /tmp/backup.tar.gz

echo "✅ 備份完成: $BACKUP_DIR/$APP_NAME-$TIMESTAMP.tar.gz"
