#!/bin/bash
# Setup script for EC2 deployment runner
# Run this on a fresh Amazon Linux 2 instance

set -e

echo "🚀 Setting up Selah EC2 Deployment Runner"
echo "========================================"

# Update system
echo "📦 Updating system packages..."
sudo yum update -y

# Install Node.js 18
echo "📦 Installing Node.js..."
curl -fsSL https://rpm.nodesource.com/setup_18.x | sudo bash -
sudo yum install -y nodejs

# Install AWS CLI v2
echo "📦 Installing AWS CLI..."
curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
unzip awscliv2.zip
sudo ./aws/install
rm -rf aws awscliv2.zip

# Install AWS CDK
echo "📦 Installing AWS CDK..."
sudo npm install -g aws-cdk

# Install PM2 for process management
echo "📦 Installing PM2..."
sudo npm install -g pm2

# Create deployment directory
echo "📁 Creating deployment directory..."
mkdir -p ~/selah-runner
cd ~/selah-runner

# Copy the runner script (assuming it's uploaded)
echo "📝 Setting up runner script..."
cat > ec2-deploy-runner.js << 'EOF'
# [Runner script will be copied here]
EOF

# Install dependencies
echo "📦 Installing Node.js dependencies..."
npm init -y
npm install express multer unzipper

# Note: AWS credentials not needed!
echo ""
echo "✅ AWS credentials will be passed securely from the client"
echo "No need to configure AWS on this instance!"
echo ""

# Create PM2 ecosystem file
cat > ecosystem.config.js << 'EOF'
module.exports = {
  apps: [{
    name: 'selah-runner',
    script: './ec2-deploy-runner.js',
    instances: 1,
    autorestart: true,
    watch: false,
    max_memory_restart: '2G',
    env: {
      NODE_ENV: 'production',
      PORT: 3000
    }
  }]
};
EOF

# Create systemd service for PM2
echo "🔧 Setting up PM2 as system service..."
pm2 startup systemd -u ec2-user --hp /home/ec2-user
pm2 save

echo ""
echo "✅ Setup complete!"
echo ""
echo "Next steps:"
echo "1. Copy ec2-deploy-runner.js to this directory"
echo "2. Start the runner: pm2 start ecosystem.config.js"
echo "3. Update Supabase Edge Function with this instance's URL"
echo "4. Configure security group to allow port 3000 from Supabase"
echo ""
echo "Benefits:"
echo "• No AWS credentials needed on EC2"
echo "• Each deployment uses client's credentials"
echo "• Supports MFA/SSO workflows"
echo "• More secure - no stored credentials"
echo ""
echo "To view logs: pm2 logs selah-runner"
echo "To monitor: pm2 monit"