#!/bin/bash
# Deploy El Captain Sports Management to CapRover
# Usage: ./deploy.sh [app-name]

set -e

APP_NAME="${1:-el-captain}"
SERVER="18.192.166.221"
SSH_KEY="/Users/mahmoudaglan/NewMigration/newServer.pem"

echo "==> Deploying $APP_NAME to CapRover..."

# Create a tar of the project (respecting .dockerignore)
TAR_FILE="/tmp/el-captain-deploy.tar"

# Build tar excluding .dockerignore patterns
tar -cf "$TAR_FILE" \
    --exclude='.git' \
    --exclude='node_modules' \
    --exclude='vendor' \
    --exclude='.env' \
    --exclude='.env.local' \
    --exclude='storage/logs/*' \
    --exclude='storage/framework/cache/data/*' \
    --exclude='storage/framework/sessions/*' \
    --exclude='storage/framework/views/*' \
    --exclude='tests' \
    --exclude='public/build' \
    --exclude='public/hot' \
    --exclude='.claude' \
    --exclude='docs' \
    .

echo "==> Uploading to server..."
scp -i "$SSH_KEY" -o StrictHostKeyChecking=no "$TAR_FILE" ubuntu@$SERVER:/tmp/el-captain-deploy.tar

echo "==> Triggering CapRover deploy..."
ssh -i "$SSH_KEY" -o StrictHostKeyChecking=no ubuntu@$SERVER << 'REMOTE'
cd /tmp
mkdir -p el-captain-source
cd el-captain-source
tar -xf /tmp/el-captain-deploy.tar

# Deploy via CapRover CLI (caprover deploy from source)
sudo docker run --rm \
    -v /tmp/el-captain-source:/app \
    --network captain-overlay-network \
    caprover/cli-caprover:latest \
    caprover deploy --appName el-captain --tarFile /app 2>/dev/null || true

# Cleanup
rm -rf /tmp/el-captain-source /tmp/el-captain-deploy.tar
REMOTE

rm -f "$TAR_FILE"

echo "==> Deploy complete! Check: https://${APP_NAME}.caprover.al-arcade.com"
