#!/bin/bash

# EaglerTiers System Services Installation Script
# For Debian 13
# This script sets up the API and Discord bot as systemd services

set -e

echo "╔════════════════════════════════════════════════════════════╗"
echo "║   EaglerTiers - System Services Setup (Debian 13)          ║"
echo "╚════════════════════════════════════════════════════════════╝"
echo ""

# Check if running as root
if [[ $EUID -ne 0 ]]; then
    echo "✗ This script must be run as root (use sudo)"
    exit 1
fi

# Update package manager
echo "✓ Updating package manager..."
apt-get update
echo ""

# Check and install Node.js if needed
echo "✓ Checking Node.js installation..."
if ! command -v node &> /dev/null; then
    echo "  Node.js not found, installing from NodeSource repository..."
    curl -fsSL https://deb.nodesource.com/setup_22.x | bash -
    apt-get install -y nodejs
    echo "  Node.js installed"
else
    NODE_VERSION=$(node -v)
    echo "  Found Node.js: $NODE_VERSION"
fi
echo ""

# Check and install MariaDB if needed
echo "✓ Checking MariaDB installation..."
if ! command -v mysql &> /dev/null; then
    echo "  MariaDB client not found, installing MariaDB server and client..."
    apt-get install -y mariadb-server mariadb-client
    systemctl start mariadb
    systemctl enable mariadb
    echo "  MariaDB installed and started"
else
    echo "  Found MariaDB/MySQL"
fi
echo ""

# Install other required dependencies
echo "✓ Installing system dependencies..."
apt-get install -y build-essential git
echo ""

echo "✓ This script will:"
echo "  - Create/update systemd service files"
echo "  - Create the eaglertiers user (if needed)"
echo "  - Set up proper permissions"
echo "  - Enable auto-start on boot"
echo ""
read -p "Continue? (y/n) " -n 1 -r
echo
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
    exit 1
fi
echo ""

# Create eaglertiers user if it doesn't exist
echo "✓ Setting up eaglertiers user..."
if ! id "eaglertiers" &>/dev/null; then
    useradd -r -s /bin/bash -d /opt/eaglertiers -m eaglertiers
    echo "  Created eaglertiers user"
else
    echo "  eaglertiers user already exists"
fi
echo ""

# Find project root (where package.json is located)
echo "✓ Finding project directory..."
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

# If script is in a subdirectory, go up to find package.json
PROJECT_ROOT="$SCRIPT_DIR"
if [ ! -f "$PROJECT_ROOT/package.json" ]; then
    if [ -f "$PROJECT_ROOT/../package.json" ]; then
        PROJECT_ROOT="$( cd "$PROJECT_ROOT/.." && pwd )"
    elif [ -f "$PROJECT_ROOT/../../package.json" ]; then
        PROJECT_ROOT="$( cd "$PROJECT_ROOT/../.." && pwd )"
    fi
fi

if [ ! -f "$PROJECT_ROOT/package.json" ]; then
    echo "✗ Could not find package.json in project root"
    echo "  Please run this script from the eaglertiers project directory"
    exit 1
fi

echo "  Found project at: $PROJECT_ROOT"
echo ""

# Copy project to /opt/eaglertiers if not already there
echo "✓ Setting up project directory..."
if [ ! -d "/opt/eaglertiers" ]; then
    mkdir -p /opt/eaglertiers
    echo "  Created /opt/eaglertiers"
fi

if [ "$PROJECT_ROOT" != "/opt/eaglertiers" ]; then
    echo "  Copying project files to /opt/eaglertiers..."
    cp -r "$PROJECT_ROOT"/* /opt/eaglertiers/ 2>/dev/null || true
    cp -r "$PROJECT_ROOT"/.[^.]* /opt/eaglertiers/ 2>/dev/null || true
    chown -R eaglertiers:eaglertiers /opt/eaglertiers
    chmod 755 /opt/eaglertiers
    echo "  Files copied and permissions set"
fi
echo ""

# Install npm dependencies if needed
echo "✓ Installing npm dependencies..."
cd /opt/eaglertiers
if [ ! -d "node_modules" ]; then
    sudo -u eaglertiers npm install --production
    echo "  Dependencies installed"
else
    echo "  Dependencies already installed"
fi
echo ""

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

# Install systemd service files
echo "✓ Installing systemd service files..."
cp "$SCRIPT_DIR/eaglertiers-api.service" /etc/systemd/system/
cp "$SCRIPT_DIR/eaglertiers-bot.service" /etc/systemd/system/
chmod 644 /etc/systemd/system/eaglertiers-api.service
chmod 644 /etc/systemd/system/eaglertiers-bot.service
systemctl daemon-reload
echo "  Service files installed and loaded"
echo ""

# Enable services
echo "✓ Enabling services..."
systemctl enable eaglertiers-api.service
systemctl enable eaglertiers-bot.service
echo "  Services enabled (will start on boot)"
echo ""

echo "╔════════════════════════════════════════════════════════════╗"
echo "║   Installation Complete!                                   ║"
echo "╚════════════════════════════════════════════════════════════╝"
echo ""
echo "Service Management Commands:"
echo ""
echo "  API Server:"
echo "    sudo systemctl start eaglertiers-api"
echo "    sudo systemctl stop eaglertiers-api"
echo "    sudo systemctl restart eaglertiers-api"
echo "    sudo systemctl status eaglertiers-api"
echo "    sudo journalctl -u eaglertiers-api -f     # View logs"
echo ""
echo "  Discord Bot:"
echo "    sudo systemctl start eaglertiers-bot"
echo "    sudo systemctl stop eaglertiers-bot"
echo "    sudo systemctl restart eaglertiers-bot"
echo "    sudo systemctl status eaglertiers-bot"
echo "    sudo journalctl -u eaglertiers-bot -f     # View logs"
echo ""
echo "  Both Together:"
echo "    sudo systemctl restart eaglertiers-api eaglertiers-bot"
echo "    sudo systemctl stop eaglertiers-api eaglertiers-bot"
echo "    sudo systemctl status eaglertiers-api eaglertiers-bot"
echo ""
echo "  View All Logs:"
echo "    sudo journalctl -u eaglertiers-api -u eaglertiers-bot -f"
echo ""
