#!/bin/bash

if [ $# -ne 1 ]; then
    echo "Usage: $0 <backup-file.tar.gz>"
    exit 1
fi

BACKUP_FILE=$1
TEMP_DIR="k8s-restore-$(date +%Y%m%d-%H%M%S)"

# Extract backup
echo "Extracting backup..."
tar -xzf "$BACKUP_FILE"
BACKUP_DIR=$(tar -tzf "$BACKUP_FILE" | head -1 | cut -f1 -d"/")

# Install k3s if not present
# if ! command -v k3s >/dev/null 2>&1; then
#     echo "Installing k3s..."
#     curl -sfL https://get.k3s.io | sh -
#     mkdir -p ~/.kube
#     sudo cp /etc/rancher/k3s/k3s.yaml ~/.kube/config
#     sudo chown $(id -u):$(id -g) ~/.kube/config
# fi

# Wait for k3s to be ready
echo "Waiting for k3s to be ready..."
kubectl wait --for=condition=Ready nodes --all --timeout=300s

# Create namespaces first
echo "Creating namespaces..."
find "$BACKUP_DIR" -mindepth 1 -maxdepth 1 -type d | while read ns_dir; do
    ns=$(basename "$ns_dir")
    if [ "$ns" != "cluster-resources" ]; then
        kubectl create namespace "$ns" --dry-run=client -o yaml | kubectl apply -f -
    fi
done

# Apply CRDs first from cluster-resources
echo "Applying CRDs..."
if [ -f "$BACKUP_DIR/cluster-resources/customresourcedefinitions.apiextensions.k8s.io.yaml" ]; then
    kubectl apply -f "$BACKUP_DIR/cluster-resources/customresourcedefinitions.apiextensions.k8s.io.yaml"
    # Wait for CRDs to be established
    sleep 10
fi

# Restore cluster-wide resources
echo "Restoring cluster-wide resources..."
find "$BACKUP_DIR/cluster-resources" -name "*.yaml" | while read resource; do
    if [[ $(basename "$resource") != "nodes.yaml" ]] && \
       [[ $(basename "$resource") != "endpoints.yaml" ]] && \
       [[ $(basename "$resource") != "customresourcedefinitions.apiextensions.k8s.io.yaml" ]]; then
        echo "Applying $(basename "$resource")..."
        kubectl apply -f "$resource"
    fi
done

# Restore namespaced resources
echo "Restoring namespaced resources..."
find "$BACKUP_DIR" -mindepth 1 -maxdepth 1 -type d | while read ns_dir; do
    ns=$(basename "$ns_dir")
    if [ "$ns" != "cluster-resources" ]; then
        echo "Restoring resources in namespace: $ns"
        find "$ns_dir" -name "*.yaml" | while read resource; do
            echo "Applying $(basename "$resource")..."
            kubectl apply -f "$resource" || true
        done
    fi
done

# Clean up
rm -rf "$BACKUP_DIR"
echo "Restore completed!"
