#!/bin/bash
# Deploy IStalk Relay Server to CapRover
# Usage: ./deploy.sh

set -e

APP_NAME="istalk-relay"
SERVER="18.192.166.221"
SSH_KEY="/Users/mahmoudaglan/NewMigration/newServer.pem"
SSH_USER="ubuntu"
SSH_CMD="ssh -i $SSH_KEY -o StrictHostKeyChecking=no $SSH_USER@$SERVER"
CAPROVER_URL="https://captain.caprover.al-arcade.com"
CAPROVER_PASSWORD="Alarcade123#"

echo "=== Deploying IStalk Relay Server to CapRover ==="

# Step 1: Get CapRover auth token
echo "[1/6] Getting auth token..."
TOKEN=$($SSH_CMD "curl -sk -X POST $CAPROVER_URL/api/v2/login \
  -H 'Content-Type: application/json' \
  -H 'x-namespace: captain' \
  -d '{\"password\":\"$CAPROVER_PASSWORD\"}'" | python3 -c "import sys,json; print(json.load(sys.stdin)['data']['token'])")

echo "Token acquired."

# Step 2: Create the app (ignore if exists)
echo "[2/6] Creating app '$APP_NAME'..."
$SSH_CMD "curl -sk -X POST $CAPROVER_URL/api/v2/user/apps/appDefinitions/register \
  -H 'Content-Type: application/json' \
  -H 'x-namespace: captain' \
  -H 'x-captain-auth: $TOKEN' \
  -d '{\"appName\":\"$APP_NAME\",\"hasPersistentData\":false}'" || true

# Step 3: Enable WebSocket support + set container port
echo "[3/6] Enabling WebSocket support..."
$SSH_CMD "curl -sk -X POST $CAPROVER_URL/api/v2/user/apps/appDefinitions/update \
  -H 'Content-Type: application/json' \
  -H 'x-namespace: captain' \
  -H 'x-captain-auth: $TOKEN' \
  -d '{\"appName\":\"$APP_NAME\",\"websocketSupport\":true,\"containerHttpPort\":3000}'"

# Step 4: Deploy via tar upload
echo "[4/6] Packaging and deploying..."
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
tar -czf /tmp/istalk-relay.tar.gz --exclude='node_modules' -C "$SCRIPT_DIR" .
scp -i $SSH_KEY -o StrictHostKeyChecking=no /tmp/istalk-relay.tar.gz $SSH_USER@$SERVER:/tmp/

$SSH_CMD "curl -sk -X POST $CAPROVER_URL/api/v2/user/apps/appData/$APP_NAME \
  -H 'x-namespace: captain' \
  -H 'x-captain-auth: $TOKEN' \
  -F 'sourceFile=@/tmp/istalk-relay.tar.gz'"

# Step 5: Enable HTTPS
echo "[5/6] Enabling HTTPS..."
sleep 10
$SSH_CMD "curl -sk -X POST $CAPROVER_URL/api/v2/user/apps/appDefinitions/enablebasedomainssl \
  -H 'Content-Type: application/json' \
  -H 'x-namespace: captain' \
  -H 'x-captain-auth: $TOKEN' \
  -d '{\"appName\":\"$APP_NAME\"}'"

# Step 6: Force HTTPS
echo "[6/6] Forcing HTTPS..."
$SSH_CMD "curl -sk -X POST $CAPROVER_URL/api/v2/user/apps/appDefinitions/update \
  -H 'Content-Type: application/json' \
  -H 'x-namespace: captain' \
  -H 'x-captain-auth: $TOKEN' \
  -d '{\"appName\":\"$APP_NAME\",\"forceSsl\":true}'"

echo ""
echo "=== Deployment complete! ==="
echo "URL: https://$APP_NAME.caprover.al-arcade.com"
echo "Health: https://$APP_NAME.caprover.al-arcade.com/health"
echo "WebSocket: wss://$APP_NAME.caprover.al-arcade.com"
