#!/bin/bash

# EaglerTiers Linux Startup Script
# This script installs dependencies and runs the application

set -e  # Exit on error

echo "╔════════════════════════════════════════╗"
echo "║   EaglerTiers - Linux Setup & Run      ║"
echo "╚════════════════════════════════════════╝"
echo ""

# Check if Node.js is installed
echo "✓ Checking Node.js installation..."
if ! command -v node &> /dev/null; then
    echo "✗ Node.js is not installed!"
    echo "  Please install Node.js >= 18 from https://nodejs.org/"
    exit 1
fi

NODE_VERSION=$(node -v)
echo "  Found Node.js: $NODE_VERSION"
echo ""

# Check if MariaDB/MySQL is installed
echo "✓ Checking MariaDB/MySQL installation..."
if ! command -v mysql &> /dev/null; then
    echo "⚠ MariaDB/MySQL client not found!"
    echo "  Install with: sudo apt-get install mariadb-server mariadb-client (Debian/Ubuntu)"
    echo "              or: sudo yum install mariadb-server mariadb (RHEL/CentOS)"
    echo "  Or start MariaDB in Docker: docker run -d -p 3306:3306 -e MYSQL_ROOT_PASSWORD=root mariadb"
    echo ""
    read -p "Continue anyway? (y/n) " -n 1 -r
    echo
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        exit 1
    fi
else
    echo "  Found MySQL/MariaDB client"
fi
echo ""

# Install npm dependencies
echo "✓ Installing npm dependencies..."
if [ ! -d "node_modules" ]; then
    npm install
    echo "  Dependencies installed successfully"
else
    echo "  Dependencies already installed"
    read -p "Run 'npm install' again to update? (y/n) " -n 1 -r
    echo
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        npm install
    fi
fi
echo ""

# Seed database
echo "✓ Setting up database..."
read -p "Seed database with sample data? (y/n) " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
    ALLOW_SEED=YES_WIPE_AND_SEED npm run seed
    echo "  Database seeded successfully"
else
    echo "  Skipping database seed"
fi
echo ""

# Start the application
echo "╔════════════════════════════════════════╗"
echo "║   Starting EaglerTiers Server          ║"
echo "╚════════════════════════════════════════╝"
echo ""
echo "  Frontend: http://localhost:3000"
echo "  API: http://localhost:3000/api"
echo ""
echo "  To run the Discord bot in another terminal:"
echo "    npm run bot"
echo ""
echo "  Press Ctrl+C to stop the server"
echo ""

npm start
