#!/bin/bash
# Simple backup script for your personal cloud

set -e
set -o pipefail

# Initialize Wild Cloud environment
if [ -z "${WC_ROOT}" ]; then
    echo "WC_ROOT is not set."
    exit 1
else
    source "${WC_ROOT}/scripts/common.sh"
    init_wild_env
fi

if `wild-config cloud.backup.root --check`; then
    export RESTIC_REPOSITORY="$(wild-config cloud.backup.root)"
else
    echo "WARNING: Could not get cloud backup root."
    exit 1
fi

if `wild-secret cloud.backupPassword --check`; then
    export RESTIC_PASSWORD="$(wild-secret cloud.backupPassword)"
else
    echo "WARNING: Could not get cloud backup secret."
    exit 1
fi

if `wild-config cloud.backup.staging --check`; then
    STAGING_DIR="$(wild-config cloud.backup.staging)"
else
    echo "WARNING: Could not get cloud backup staging directory."
    exit 1
fi

echo "Backup at '$RESTIC_REPOSITORY'."

# Initialize the repository if needed.
echo "Checking if restic repository exists..."
if restic cat config >/dev/null 2>&1; then
    echo "Using existing backup repository."
else
    echo "No existing backup repository found. Initializing restic repository..."
    restic init
    echo "Repository initialized successfully."
fi

# Backup entire WC_HOME.
restic --verbose --tag wild-cloud --tag wc-home --tag "$(date +%Y-%m-%d)" backup $WC_HOME
# TODO: Ignore wild cloud cache?

mkdir -p "$STAGING_DIR"

# Run backup for all apps at once
echo "Running backup for all apps..."
wild-app-backup --all

# Upload each app's backup to restic individually  
for app_dir in "$STAGING_DIR"/apps/*; do
    if [ ! -d "$app_dir" ]; then
        continue
    fi
    app="$(basename "$app_dir")"
    echo "Uploading backup for app: $app"
    restic --verbose --tag wild-cloud --tag "$app" --tag "$(date +%Y-%m-%d)" backup "$app_dir"
    echo "Backup for app '$app' completed."
done

# Back up Kubernetes resources
# kubectl get all -A -o yaml > "$BACKUP_DIR/all-resources.yaml"
# kubectl get secrets -A -o yaml > "$BACKUP_DIR/secrets.yaml"
# kubectl get configmaps -A -o yaml > "$BACKUP_DIR/configmaps.yaml"

# Back up persistent volumes
# TODO: Add logic to back up persistent volume data

echo "Backup completed: $BACKUP_DIR"
