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

APP_NAME="vaultwarden"
BASE_DIR="$(cd "$(dirname "$0")" && pwd)"
BACKUP_DIR="$BASE_DIR/backup"

if [ $# -eq 0 ]; then
    echo "用法: $0 <backup-file>"
    echo ""
    echo "可用備份:"
    ls -lh "$BACKUP_DIR/"*.tar.gz 2>/dev/null || echo "無備份檔案"
    exit 1
fi

BACKUP_FILE="$1"

if [ ! -f "$BACKUP_FILE" ]; then
    echo "❌ 備份檔案不存在: $BACKUP_FILE"
    exit 1
fi

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

echo "📥 還原 $APP_NAME 從 $BACKUP_FILE..."

kubectl cp "$BACKUP_FILE" $POD:/tmp/restore.tar.gz
kubectl exec $POD -- tar xzf /tmp/restore.tar.gz -C /
kubectl exec $POD -- rm /tmp/restore.tar.gz

echo "✅ 還原完成，請重啟 Pod"
kubectl rollout restart deployment/$APP_NAME
