#!/bin/bash

# Define the S3 bucket paths and local backup directories
BACKUP_PATHS=(
  "s3://backups"
  "s3://test"
)
LOCAL_BASE_DIR="$HOME/Downloads/velero.backups"

# Function to download the latest backup from an S3 path
download_latest_backup() {
  local s3_path="$1"
  local local_dir
  local_dir="$2/$(basename "$s3_path")"

  # Extract bucket name without s3:// prefix
  local bucket_name
  bucket_name=$(echo "$s3_path" | sed 's/^s3:\/\///')

  echo "Processing bucket: $bucket_name"

  # Create the local directory if it doesn't exist
  mkdir -p "$local_dir"

  # Clear the target directory
  echo "Clearing directory: $local_dir"
  rm -rf "${local_dir:?}"/*

  # Find the latest backup directory
  echo "Finding latest backup in $bucket_name/backups/"
  local latest_backup_dir
  latest_backup_dir=$(aws s3 ls "$s3_path/backups/" --recursive |
    grep "\.backup/.*.tar.gz$" |
    sort -k1,2 |
    tail -n1 |
    awk '{print $4}' |
    sed 's/\/[^/]*$/\//') # Extract directory path

  if [[ -z $latest_backup_dir ]]; then
    echo "No backup directories found in $bucket_name/backups/"
    return 1
  fi

  # Remove the filename to get just the directory
  local backup_dir
  backup_dir="$(echo "$latest_backup_dir" | sed 's/backups\///')"
  echo "Latest backup directory: $backup_dir"

  # Download all files from the latest backup directory
  echo "Downloading files from s3://$bucket_name/backups/$backup_dir"

  if aws s3 sync "s3://$bucket_name/backups/$backup_dir" "$local_dir/"; then
    echo "Successfully downloaded backup to $local_dir"
    echo "Contents of $local_dir:"
    ls -la "$local_dir"
  else
    echo "Error downloading backup from $bucket_name/backups/$backup_dir"
    return 1
  fi
}

# Main execution
echo "Starting backup download process..."

# Process each backup path
for s3_path in "${BACKUP_PATHS[@]}"; do
  download_latest_backup "$s3_path" "$LOCAL_BASE_DIR"
done

echo -e "\nVerifying final backup contents:"
for dir in "$LOCAL_BASE_DIR"/*; do
  if [ -d "$dir" ]; then
    echo -e "\nContents of $(basename "$dir"):"
    ls -la "$dir"
  fi
done

echo "Backup process completed."
