#!/bin/bash
set -e

echo "[SETUP] Starting EC2 instance setup..."

# Install Docker if not already installed
if ! command -v docker &> /dev/null; then
    echo "[SETUP] Installing Docker..."
    yum update -y
    yum install -y docker
    systemctl start docker
    systemctl enable docker
    usermod -aG docker ec2-user
else
    echo "[SETUP] Docker already installed"
fi

# Install Docker Compose if not already installed
if ! command -v docker-compose &> /dev/null; then
    echo "[SETUP] Installing Docker Compose..."
    curl -L "https://github.com/docker/compose/releases/latest/download/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
    chmod +x /usr/local/bin/docker-compose
else
    echo "[SETUP] Docker Compose already installed"
fi

# Get region from instance metadata
REGION=$(curl -s http://169.254.169.254/latest/meta-data/placement/region)
echo "[SETUP] Region: $REGION"

# Authenticate Docker to ECR
echo "[SETUP] Authenticating to ECR..."
aws ecr get-login-password --region $REGION | docker login --username AWS --password-stdin {{ecr_registry}}

# Download docker-compose.yml from S3
echo "[SETUP] Downloading docker-compose.yml..."
aws s3 cp s3://{{deployment_bucket}}/{{project_name}}/compose/docker-compose.yml /home/ec2-user/docker-compose.yml

# Pull the Docker image
echo "[SETUP] Pulling Docker image..."
cd /home/ec2-user
docker-compose pull

# Start the application
echo "[SETUP] Starting application..."
docker-compose up -d

echo "[SETUP] Setup complete! Application is running."
