#!/bin/bash
set -e

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
PROJECT_DIR="$(dirname "$SCRIPT_DIR")"
BUILD_DIR=$(mktemp -d)
APP_NAME="el-captain-docs"
SERVER="ubuntu@18.192.166.221"
SSH_KEY="/Users/mahmoudaglan/NewMigration/newServer.pem"
SSH_CMD="ssh -i $SSH_KEY -o StrictHostKeyChecking=no $SERVER"

echo "==> Preparing build context..."
cp "$SCRIPT_DIR/index.php" "$BUILD_DIR/"
cp "$SCRIPT_DIR/.htaccess" "$BUILD_DIR/"
cp "$SCRIPT_DIR/Dockerfile" "$BUILD_DIR/"
mkdir -p "$BUILD_DIR/docs/ar"
cp "$PROJECT_DIR/docs/ar/"*.md "$BUILD_DIR/docs/ar/"

# Remove macOS metadata
find "$BUILD_DIR" -name '._*' -delete
find "$BUILD_DIR" -name '.DS_Store' -delete

echo "==> Creating tarball..."
cd "$BUILD_DIR"
tar czf /tmp/el-captain-docs.tar.gz .

echo "==> Uploading to server..."
scp -i "$SSH_KEY" -o StrictHostKeyChecking=no /tmp/el-captain-docs.tar.gz "$SERVER:/tmp/"

echo "==> Building and deploying on server..."
$SSH_CMD bash -s <<'REMOTE'
set -e

rm -rf /tmp/el-captain-docs-build
mkdir -p /tmp/el-captain-docs-build
cd /tmp/el-captain-docs-build
tar xzf /tmp/el-captain-docs.tar.gz 2>/dev/null
find . -name '._*' -delete

echo "Building Docker image..."
sudo docker build -t img-captain--el-captain-docs:latest . 2>&1 | tail -3

echo "Updating service..."
sudo docker service update --image img-captain--el-captain-docs:latest --force srv-captain--el-captain-docs 2>&1 | tail -3

echo ""
echo "Verifying..."
sleep 3
CID=$(sudo docker ps -q --filter "name=srv-captain--el-captain-docs")
TITLE=$(sudo docker exec $CID curl -s http://localhost/ | grep -o '<title>[^<]*</title>')
echo "Live: $TITLE"

rm -rf /tmp/el-captain-docs-build /tmp/el-captain-docs.tar.gz
REMOTE

rm -rf "$BUILD_DIR" /tmp/el-captain-docs.tar.gz

echo ""
echo "==> Done! https://el-captain-docs.caprover.al-arcade.com"
