#!/bin/bash

# Deployment Script for ASF TestArena
# Usage: ./deploy.sh

set -e # Exit on error

echo "Starting deployment..."

# Function to run docker-compose with correct permissions
run_compose() {
    if groups | grep -q '\bdocker\b'; then
        docker-compose "$@"
    else
        echo "User not in docker group, using sudo for docker-compose..."
        sudo docker-compose "$@"
    fi
}

# Check for docker-compose
if ! command -v docker-compose &> /dev/null; then
    echo "Error: docker-compose is not installed."
    exit 1
fi

# 1. Pull latest changes
echo "Pulling latest changes from git..."
git pull

# 2. Build Frontend using Docker (No local Node.js required)
echo "Building frontend using Docker..."
run_compose run --rm frontend-builder

# 3. Deploy Frontend
echo "Deploying frontend to /var/www/testarena..."
# Ensure directory exists
if [ ! -d "/var/www/testarena" ]; then
    echo "Creating /var/www/testarena..."
    sudo mkdir -p /var/www/testarena
    sudo chown $USER:$USER /var/www/testarena
fi

# Copy files
if [ -d "frontend/dist" ]; then
    sudo cp -r frontend/dist/* /var/www/testarena/
else
    echo "Error: frontend/dist directory not found. Build failed?"
    exit 1
fi

# 4. Restart Backend
echo "Restarting backend services..."
# Ensure results directory exists for Nginx
if [ ! -d "results" ]; then
    mkdir -p results
    chmod 755 results
fi

run_compose down
run_compose up -d --build

# 5. Reload Nginx (Optional, if config changed)
echo "Reloading Nginx..."
sudo systemctl reload nginx

echo "Deployment complete! Access at http://asf-testarena.duckdns.org"
