#!/usr/bin/env bash

#
# Linux BenchTools - Installation Script
# Automated installation and setup
#

set -e

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

echo -e "${GREEN}"
cat <<'EOF'
╔════════════════════════════════════════════════════════════╗
║                                                            ║
║          Linux BenchTools - Installation Script           ║
║                                                            ║
║       Self-hosted benchmarking for Linux machines         ║
║                                                            ║
╚════════════════════════════════════════════════════════════╝
EOF
echo -e "${NC}"

# Check if running as root
if [[ $EUID -eq 0 ]]; then
   echo -e "${RED}[ERROR]${NC} This script should NOT be run as root"
   exit 1
fi

# Check for Docker
echo -e "${GREEN}[INFO]${NC} Checking prerequisites..."

if ! command -v docker &> /dev/null; then
    echo -e "${RED}[ERROR]${NC} Docker is not installed."
    echo "Please install Docker first:"
    echo "  curl -fsSL https://get.docker.com | sh"
    exit 1
fi

if ! command -v docker compose &> /dev/null; then
    echo -e "${RED}[ERROR]${NC} Docker Compose is not available."
    echo "Please install Docker Compose plugin"
    exit 1
fi

echo -e "${GREEN}[SUCCESS]${NC} Docker and Docker Compose are installed"

# Create directories
echo -e "${GREEN}[INFO]${NC} Creating directories..."
mkdir -p backend/data
mkdir -p uploads

# Generate .env file if it doesn't exist
if [[ ! -f .env ]]; then
    echo -e "${GREEN}[INFO]${NC} Generating .env file..."

    API_TOKEN=$(openssl rand -hex 32)

    cat > .env <<EOF
# Linux BenchTools Configuration
# Generated on $(date)

API_TOKEN=${API_TOKEN}
DATABASE_URL=sqlite:////app/data/data.db
UPLOAD_DIR=/app/uploads
BACKEND_PORT=8007
FRONTEND_PORT=8087
EOF

    echo -e "${GREEN}[SUCCESS]${NC} .env file created"
else
    echo -e "${YELLOW}[WARN]${NC} .env file already exists, skipping generation"
fi

# Load environment variables
if [[ -f .env ]]; then
    export $(cat .env | grep -v '^#' | xargs)
fi

# Build and start containers
echo -e "${GREEN}[INFO]${NC} Building Docker images..."
docker compose build

echo -e "${GREEN}[INFO]${NC} Starting services..."
docker compose up -d

# Wait for backend to be ready
echo -e "${GREEN}[INFO]${NC} Waiting for backend to be ready..."
sleep 5

MAX_RETRIES=30
RETRY_COUNT=0

while [[ $RETRY_COUNT -lt $MAX_RETRIES ]]; do
    if curl -s http://localhost:${BACKEND_PORT}/api/health > /dev/null 2>&1; then
        echo -e "${GREEN}[SUCCESS]${NC} Backend is ready!"
        break
    fi

    RETRY_COUNT=$((RETRY_COUNT + 1))
    echo -ne "${YELLOW}[WAIT]${NC} Backend not ready yet... ($RETRY_COUNT/$MAX_RETRIES)\r"
    sleep 1
done

if [[ $RETRY_COUNT -eq $MAX_RETRIES ]]; then
    echo -e "\n${RED}[ERROR]${NC} Backend failed to start within expected time"
    echo "Check logs with: docker compose logs backend"
    exit 1
fi

# Display success message
echo ""
echo -e "${GREEN}╔════════════════════════════════════════════════════════════╗${NC}"
echo -e "${GREEN}║                                                            ║${NC}"
echo -e "${GREEN}║          Installation completed successfully! 🎉          ║${NC}"
echo -e "${GREEN}║                                                            ║${NC}"
echo -e "${GREEN}╚════════════════════════════════════════════════════════════╝${NC}"
echo ""
echo -e "${GREEN}Access Points:${NC}"
echo -e "  Backend API:  http://localhost:${BACKEND_PORT}"
echo -e "  Frontend UI:  http://localhost:${FRONTEND_PORT}"
echo -e "  API Docs:     http://localhost:${BACKEND_PORT}/docs"
echo ""
echo -e "${GREEN}API Token:${NC}"
echo -e "  ${YELLOW}${API_TOKEN}${NC}"
echo ""
echo -e "${GREEN}Next Steps:${NC}"
echo -e "  1. Open http://localhost:${FRONTEND_PORT} in your browser"
echo -e "  2. Run a benchmark on a machine with:"
echo ""
echo -e "     ${YELLOW}curl -s http://YOUR_SERVER:${FRONTEND_PORT}/scripts/bench.sh | bash -s -- \\${NC}"
echo -e "     ${YELLOW}  --server http://YOUR_SERVER:${BACKEND_PORT}/api/benchmark \\${NC}"
echo -e "     ${YELLOW}  --token \"${API_TOKEN}\"${NC}"
echo ""
echo -e "${GREEN}Useful Commands:${NC}"
echo -e "  View logs:      docker compose logs -f"
echo -e "  Stop services:  docker compose down"
echo -e "  Restart:        docker compose restart"
echo -e "  Update:         git pull && docker compose up -d --build"
echo ""
echo -e "${GREEN}Documentation:${NC}"
echo -e "  README.md"
echo -e "  STRUCTURE.md"
echo -e "  01_vision_fonctionnelle.md ... 10_roadmap_evolutions.md"
echo ""
echo -e "${GREEN}Have fun benchmarking! 🚀${NC}"
echo ""
