#!/bin/bash

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

set -e # Exit on error

echo "Starting deployment..."

# Check for required commands
if ! command -v npm &> /dev/null; then
    echo "Error: npm is not installed. Please install Node.js and npm."
    exit 1
fi

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
echo "Building frontend..."
cd frontend
npm install
npm run build
cd ..

# 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..."
# Use sudo for docker-compose if needed
if groups | grep -q '\bdocker\b'; then
    docker-compose down
    docker-compose up -d --build
else
    echo "User not in docker group, using sudo..."
    sudo docker-compose down
    sudo docker-compose up -d --build
fi

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

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