#!/bin/bash

# Update system
yum update -y

# Install Docker
amazon-linux-extras install docker -y
service docker start
usermod -a -G docker ec2-user
chkconfig docker on

# Install 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

# Configure AWS CLI
aws configure set region ${aws_region}

# Login to ECR
aws ecr get-login-password --region ${aws_region} | docker login --username AWS --password-stdin ${ecr_url}

# Create environment file
cat > /home/ec2-user/.env <<EOF
DATABASE_URL=${database_url}
JWT_SECRET=${jwt_secret}
ADMIN_PASSWORD=${admin_password}
NODE_ENV=production
PORT=80
NODE_TLS_REJECT_UNAUTHORIZED=0
EOF

# Create docker-compose file
cat > /home/ec2-user/docker-compose.yml <<EOF
version: '3.8'
services:
  api:
    image: ${ecr_url}:latest
    ports:
      - "80:80"
    env_file: .env
    restart: always
EOF

# Start the API
cd /home/ec2-user
docker-compose pull
docker-compose up -d

# Setup auto-restart on reboot
cat > /etc/systemd/system/api.service <<EOF
[Unit]
Description=Filamenteka API
After=docker.service
Requires=docker.service

[Service]
Type=oneshot
RemainAfterExit=yes
WorkingDirectory=/home/ec2-user
ExecStartPre=/usr/local/bin/docker-compose pull
ExecStart=/usr/local/bin/docker-compose up -d
ExecStop=/usr/local/bin/docker-compose down
TimeoutStartSec=0

[Install]
WantedBy=multi-user.target
EOF

systemctl enable api.service

# Add cron job to update container every 5 minutes
echo "*/5 * * * * cd /home/ec2-user && /usr/bin/aws ecr get-login-password --region ${aws_region} | /usr/bin/docker login --username AWS --password-stdin ${ecr_url} && /usr/local/bin/docker-compose pull && /usr/local/bin/docker-compose up -d" | crontab -