#!/usr/bin/env bash
set -e

BACKUP_DIR="./backup"

if [ $# -ne 1 ]; then
  echo "❌ Usage: ./restore.sh <backup-file>"
  echo
  echo "Example:"
  echo "  ./restore.sh opengist-20250101-1200.tar.gz"
  exit 1
fi

BACKUP_FILE="${BACKUP_DIR}/$1"

if [ ! -f "${BACKUP_FILE}" ]; then
  echo "❌ Backup file not found: ${BACKUP_FILE}"
  exit 1
fi

echo "⚠️  WARNING"
echo "This will OVERWRITE data in /opengist inside the PVC."
echo "Backup file: ${BACKUP_FILE}"
echo
read -p "Type YES to continue: " CONFIRM

if [ "${CONFIRM}" != "YES" ]; then
  echo "❌ Restore aborted"
  exit 1
fi

echo "🛑 Scaling down OpenGist deployment..."
kubectl scale deployment opengist --replicas=0

echo "⏳ Waiting for pod termination..."
kubectl wait --for=delete pod -l app=opengist --timeout=60s || true

echo "📦 Starting restore process..."

# 使用暫時 helper pod 掛載同一顆 PVC
cat <<EOF | kubectl apply -f -
apiVersion: v1
kind: Pod
metadata:
  name: opengist-restore
spec:
  restartPolicy: Never
  containers:
    - name: restore
      image: alpine:3.20
      command: ["sleep", "3600"]
      volumeMounts:
        - name: data-vol
          mountPath: /opengist
  volumes:
    - name: data-vol
      persistentVolumeClaim:
        claimName: opengist-pvc
EOF

echo "⏳ Waiting for restore pod to be ready..."
kubectl wait --for=condition=Ready pod/opengist-restore --timeout=60s

echo "🧹 Cleaning existing data..."
kubectl exec opengist-restore -- rm -rf /opengist/*

echo "📂 Restoring backup..."
kubectl exec -i opengist-restore -- \
  tar xzf - -C / < "${BACKUP_FILE}"

echo "🧹 Cleaning up restore pod..."
kubectl delete pod opengist-restore

echo "🚀 Scaling OpenGist back up..."
kubectl scale deployment opengist --replicas=1

echo "⏳ Waiting for OpenGist to be ready..."
kubectl rollout status deployment/opengist

echo "✅ Restore completed successfully"

