#!/bin/bash

echo "Deploying API update to EC2 instance..."

# Get instance ID
INSTANCE_ID="i-03956ecf32292d7d9"

# Create update script
cat > /tmp/update-api.sh << 'EOF'
#!/bin/bash
cd /home/ubuntu/filamenteka-api

# Backup current server.js
cp server.js server.js.backup

# Download the updated server.js from Gitea
curl -o server.js https://git.demirix.dev/dax/Filamenteka/raw/branch/main/api/server.js

# Restart the service
sudo systemctl restart node-api

echo "API server updated and restarted"
EOF

# Send command to EC2 instance
aws ssm send-command \
    --region eu-central-1 \
    --instance-ids "$INSTANCE_ID" \
    --document-name "AWS-RunShellScript" \
    --parameters "commands=[
        'cd /home/ubuntu/filamenteka-api',
        'cp server.js server.js.backup',
        'curl -o server.js https://git.demirix.dev/dax/Filamenteka/raw/branch/main/api/server.js',
        'sudo systemctl restart node-api',
        'sudo systemctl status node-api'
    ]" \
    --output json

echo "Command sent. Check AWS Systems Manager for execution status."