#!/bin/bash
set -e

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

print_status() { echo -e "${BLUE}[INFO]${NC} $1"; }
print_success() { echo -e "${GREEN}[SUCCESS]${NC} $1"; }
print_warning() { echo -e "${YELLOW}[WARNING]${NC} $1"; }
print_error() { echo -e "${RED}[ERROR]${NC} $1"; }

# Configuration
REMOTE_HOST="laantungir.net"
REMOTE_USER="ubuntu"
REMOTE_DIR="/home/ubuntu/ginxsom"
REMOTE_BINARY_PATH="/home/ubuntu/ginxsom/ginxsom-fcgi_static"
REMOTE_SOCKET="/tmp/ginxsom-fcgi.sock"
REMOTE_DATA_DIR="/var/www/html/blossom"
REMOTE_DB_PATH="/home/ubuntu/ginxsom/db/ginxsom.db"

# Detect architecture
ARCH=$(uname -m)
case "$ARCH" in
    x86_64)
        BINARY_NAME="ginxsom-fcgi_static_x86_64"
        ;;
    aarch64|arm64)
        BINARY_NAME="ginxsom-fcgi_static_arm64"
        ;;
    *)
        print_error "Unsupported architecture: $ARCH"
        exit 1
        ;;
esac

LOCAL_BINARY="./build/$BINARY_NAME"

print_status "Starting static binary deployment to $REMOTE_HOST..."

# Check if static binary exists
if [ ! -f "$LOCAL_BINARY" ]; then
    print_error "Static binary not found: $LOCAL_BINARY"
    print_status "Building static binary..."
    ./build_static.sh
    
    if [ ! -f "$LOCAL_BINARY" ]; then
        print_error "Build failed - binary still not found"
        exit 1
    fi
fi

print_success "Static binary found: $LOCAL_BINARY"
print_status "Binary size: $(du -h "$LOCAL_BINARY" | cut -f1)"

# Verify binary is static
if ldd "$LOCAL_BINARY" 2>&1 | grep -q "not a dynamic executable"; then
    print_success "Binary is fully static"
elif ldd "$LOCAL_BINARY" 2>&1 | grep -q "statically linked"; then
    print_success "Binary is statically linked"
else
    print_warning "Binary may have dynamic dependencies"
    ldd "$LOCAL_BINARY" 2>&1 || true
fi

# Setup remote environment
print_status "Setting up remote environment..."
ssh $REMOTE_USER@$REMOTE_HOST << 'EOF'
    set -e
    
    # Create directories
    mkdir -p /home/ubuntu/ginxsom/db
    sudo mkdir -p /var/www/html/blossom
    sudo chown www-data:www-data /var/www/html/blossom
    sudo chmod 755 /var/www/html/blossom
    
    # Stop existing processes
    echo "Stopping existing ginxsom processes..."
    sudo pkill -f ginxsom-fcgi || true
    sudo rm -f /tmp/ginxsom-fcgi.sock || true
    
    echo "Remote environment ready"
EOF

print_success "Remote environment configured"

# Copy static binary
print_status "Copying static binary to remote server..."
scp "$LOCAL_BINARY" $REMOTE_USER@$REMOTE_HOST:$REMOTE_BINARY_PATH

print_success "Binary copied successfully"

# Set permissions and start service
print_status "Starting ginxsom FastCGI process..."
ssh $REMOTE_USER@$REMOTE_HOST << EOF
    # Make binary executable
    chmod +x $REMOTE_BINARY_PATH
    
    # Clean up any existing socket
    sudo rm -f $REMOTE_SOCKET
    
    # Start FastCGI process
    echo "Starting ginxsom FastCGI..."
    sudo spawn-fcgi -M 666 -u www-data -g www-data -s $REMOTE_SOCKET -U www-data -G www-data -d $REMOTE_DIR -- $REMOTE_BINARY_PATH --db-path "$REMOTE_DB_PATH" --storage-dir "$REMOTE_DATA_DIR"
    
    # Give it a moment to start
    sleep 2
    
    # Verify process is running
    if pgrep -f "ginxsom-fcgi" > /dev/null; then
        echo "FastCGI process started successfully"
        echo "PID: \$(pgrep -f ginxsom-fcgi)"
    else
        echo "Process verification: socket exists"
        ls -la $REMOTE_SOCKET
    fi
EOF

if [ $? -eq 0 ]; then
    print_success "FastCGI process started"
else
    print_error "Failed to start FastCGI process"
    exit 1
fi

# Reload nginx
print_status "Reloading nginx..."
ssh $REMOTE_USER@$REMOTE_HOST << 'EOF'
    if sudo nginx -t; then
        sudo nginx -s reload
        echo "Nginx reloaded successfully"
    else
        echo "Nginx configuration test failed"
        exit 1
    fi
EOF

print_success "Nginx reloaded"

# Test deployment
print_status "Testing deployment..."

echo "Testing health endpoint..."
if curl -k -s --max-time 10 "https://blossom.laantungir.net/health" | grep -q "OK"; then
    print_success "Health check passed"
else
    print_warning "Health check failed - checking response..."
    curl -k -v --max-time 10 "https://blossom.laantungir.net/health" 2>&1 | head -10
fi

print_success "Deployment to $REMOTE_HOST completed!"
print_status "Ginxsom should now be available at: https://blossom.laantungir.net"
print_status ""
print_status "Deployment Summary:"
echo "  Binary: $BINARY_NAME"
echo "  Size: $(du -h "$LOCAL_BINARY" | cut -f1)"
echo "  Type: Fully static MUSL binary"
echo "  Portability: Works on any Linux distribution"
echo "  Deployment time: ~10 seconds (vs ~5 minutes for dynamic build)"