#!/bin/bash
# Configuration
LOCALSTACK_ENDPOINT="https://nexus.ellisbs.co.uk:4566"
BACKUP_DIR="$HOME/ian/tmp/s3_backup_$(date +%Y%m%d_%H%M%S)"

# Create backup directory
mkdir -p "$BACKUP_DIR"

# Get list of all buckets
BUCKETS=$(aws --endpoint-url=$LOCALSTACK_ENDPOINT s3api list-buckets --query "Buckets[].Name" --output text)

# Save bucket list
echo "$BUCKETS" >"$BACKUP_DIR/bucket_list.txt"

# Backup each bucket
for BUCKET in $BUCKETS; do
  echo "Backing up bucket: $BUCKET"

  # Create directory for bucket
  mkdir -p "$BACKUP_DIR/$BUCKET"

  # Save bucket configuration (ACLs, CORS, etc.)
  aws --endpoint-url=$LOCALSTACK_ENDPOINT s3api get-bucket-acl --bucket "$BUCKET" >"$BACKUP_DIR/$BUCKET/acl.json" 2>/dev/null
  aws --endpoint-url=$LOCALSTACK_ENDPOINT s3api get-bucket-cors --bucket "$BUCKET" >"$BACKUP_DIR/$BUCKET/cors.json" 2>/dev/null
  aws --endpoint-url=$LOCALSTACK_ENDPOINT s3api get-bucket-policy --bucket "$BUCKET" >"$BACKUP_DIR/$BUCKET/policy.json" 2>/dev/null

  # Download all objects
  aws --endpoint-url=$LOCALSTACK_ENDPOINT s3 cp "s3://$BUCKET" "$BACKUP_DIR/$BUCKET/objects" --recursive

  # Save metadata about objects
  aws --endpoint-url=$LOCALSTACK_ENDPOINT s3api list-objects-v2 --bucket "$BUCKET" >"$BACKUP_DIR/$BUCKET/objects_metadata.json"
done

echo "Backup completed at $BACKUP_DIR"
