#!/bin/bash
# AegisOne MAX Bot — Deploy Script
# Usage: bash max_bot_deploy.sh

set -e

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
PROJECT_DIR="/opt/projects/aegisone-py"
REMOTE_USER="angel"
REMOTE_HOST="81.177.141.34"

echo "=== MAX Bot Deploy ==="
echo "Building and packaging max_bot..."

cd "$SCRIPT_DIR"

# Create tar archive
cd "$PROJECT_DIR"
tar czf /tmp/max_bot_update.tar.gz \
    -C "$SCRIPT_DIR/.." max_bot/ \
    --exclude max_bot/__pycache__ \
    --exclude max_bot/.pytest_cache \
    --exclude "max_bot/*.pyc" \
    --exclude max_bot/tests

echo "Copying to server..."
scp /tmp/max_bot_update.tar.gz "$REMOTE_USER@$REMOTE_HOST:/tmp/"
ssh "$REMOTE_USER@$REMOTE_HOST" << 'EOF'
    set -e
    PROJECT="/opt/projects/aegisone-py/max_bot"
    BACKUP="/opt/projects/backups/max_bot_$(date +%Y%m%d_%H%M%S)"

    echo "Creating backup..."
    if [ -d "$PROJECT" ]; then
        mkdir -p "/opt/projects/backups"
        cp -a "$PROJECT" "$BACKUP"
    fi

    echo "Extracting update..."
    mkdir -p "$PROJECT"
    tar xzf /tmp/max_bot_update.tar.gz -C /opt/projects/aegisone-py/

    echo "Rebuilding and restarting container..."
    cd "$PROJECT"
    docker compose down 2>/dev/null || true
    docker compose build --no-cache --network host
    docker compose up -d

    echo "Checking health..."
    sleep 5
    for i in 1 2 3 4 5; do
        HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" https://max.aegisone.ru/health || echo "000")
        if [ "$HTTP_CODE" = "200" ]; then
            echo "Health check PASSED (HTTP $HTTP_CODE)"
            break
        fi
        echo "Waiting... attempt $i/5"
        sleep 3
    done

    echo "Deploy complete!"
EOF

echo "=== Done ==="
