#!/bin/bash
# Configuration
LOCALSTACK_ENDPOINT="https://nexus.ellisbs.co.uk:4566"
BACKUP_DIR=$1

if [ -z "$BACKUP_DIR" ]; then
  echo "Usage: $0 <backup_directory>"
  exit 1
fi

if [ ! -d "$BACKUP_DIR" ]; then
  echo "Backup directory does not exist: $BACKUP_DIR"
  exit 1
fi

# Read bucket list
BUCKETS=$(cat "$BACKUP_DIR/bucket_list.txt")

# Restore each bucket
for BUCKET in $BUCKETS; do
  echo "Restoring bucket: $BUCKET"

  # Create bucket
  aws --endpoint-url=$LOCALSTACK_ENDPOINT s3 mb "s3://$BUCKET"

  # Restore bucket configuration
  if [ -f "$BACKUP_DIR/$BUCKET/acl.json" ]; then
    aws --endpoint-url=$LOCALSTACK_ENDPOINT s3api put-bucket-acl --bucket "$BUCKET" --cli-input-json "$(cat "$BACKUP_DIR/$BUCKET/acl.json")" 2>/dev/null
  fi

  if [ -f "$BACKUP_DIR/$BUCKET/cors.json" ]; then
    aws --endpoint-url=$LOCALSTACK_ENDPOINT s3api put-bucket-cors --bucket "$BUCKET" --cli-input-json "$(cat "$BACKUP_DIR/$BUCKET/cors.json")" 2>/dev/null
  fi

  if [ -f "$BACKUP_DIR/$BUCKET/policy.json" ]; then
    aws --endpoint-url=$LOCALSTACK_ENDPOINT s3api put-bucket-policy --bucket "$BUCKET" --policy "$(cat "$BACKUP_DIR/$BUCKET/policy.json")" 2>/dev/null
  fi

  # Upload all objects
  if [ -d "$BACKUP_DIR/$BUCKET/objects" ]; then
    aws --endpoint-url=$LOCALSTACK_ENDPOINT s3 cp "$BACKUP_DIR/$BUCKET/objects" "s3://$BUCKET" --recursive
  fi
done

echo "Restore completed from $BACKUP_DIR"
