#!/bin/bash
# DigitalOcean Spaces Setup Script
# Run this script to create and configure the Spaces bucket

set -e

echo "==================================="
echo "DigitalOcean Spaces Setup"
echo "==================================="

# Check if AWS CLI is installed
if ! command -v aws &> /dev/null; then
    echo "AWS CLI not found. Installing..."
    sudo apt-get update
    sudo apt-get install -y awscli
fi

# Configure AWS CLI profile for DigitalOcean Spaces
echo "Configuring AWS CLI profile 'do-tor1'..."
aws --profile do-tor1 configure set aws_access_key_id DO801P4R8QXYMY4CE8WZ
aws --profile do-tor1 configure set aws_secret_access_key nstEJv0uZcxd/RXQhOXq9eruaJmeqsbsItFAd35tNQ0
aws --profile do-tor1 configure set endpoint_url https://nyc3.digitaloceanspaces.com
aws --profile do-tor1 configure set region nyc3

echo "AWS CLI profile configured!"

# Create the bucket
echo "Creating bucket 'smoothschedule'..."
if aws --profile do-tor1 s3 mb s3://smoothschedule 2>/dev/null; then
    echo "Bucket created successfully!"
else
    echo "Bucket may already exist or there was an error."
fi

# Set bucket ACL to public-read
echo "Setting bucket ACL to public-read..."
aws --profile do-tor1 s3api put-bucket-acl --bucket smoothschedule --acl public-read

# Configure CORS
echo "Configuring CORS..."
cat > /tmp/cors.json <<'EOF'
{
  "CORSRules": [
    {
      "AllowedOrigins": ["https://smoothschedule.com", "https://*.smoothschedule.com"],
      "AllowedMethods": ["GET", "PUT", "POST", "DELETE", "HEAD"],
      "AllowedHeaders": ["*"],
      "MaxAgeSeconds": 3000
    }
  ]
}
EOF

aws --profile do-tor1 s3api put-bucket-cors --bucket smoothschedule --cors-configuration file:///tmp/cors.json
rm /tmp/cors.json

echo ""
echo "==================================="
echo "Setup Complete!"
echo "==================================="
echo "Bucket URL: https://smoothschedule.nyc3.digitaloceanspaces.com"
echo "CDN URL: https://smoothschedule.nyc3.cdn.digitaloceanspaces.com (if CDN enabled)"
echo ""
echo "Next steps:"
echo "1. Verify bucket: aws --profile do-tor1 s3 ls s3://smoothschedule/"
echo "2. Deploy your application"
echo "3. Run: docker compose -f docker-compose.production.yml exec django python manage.py collectstatic --noinput"
