#!/bin/bash
# install_service.sh - Installs the inventory system as a standalone systemd service

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

echo "⚙️  Installing TFM aInventory as a Standalone Linux service..."

# Detect working directory
WORKING_DIR="$(pwd)"

# 1. Dependency Checks
echo "🔍 Checking dependencies..."
for cmd in python3 node npm; do
    if ! command -v $cmd &> /dev/null; then
        echo "❌ $cmd not found! Please install it before proceeding."
        exit 1
    fi
done

# 2. Setup Backend Environment
echo "🐍 Setting up Python Virtual Environment..."
if [ ! -d ".venv" ]; then
    python3 -m venv .venv
fi
source .venv/bin/activate
pip install -q --upgrade pip
pip install -q -r backend/requirements.txt

# 3. Setup Frontend Environment
echo "📦 Installing Node dependencies (this may take a minute)..."
cd frontend
npm install --quiet
echo "🏗️  Building Frontend for Production (Next.js build)..."
npm run build
cd ..

# 4. Create the final service file from template
TEMPLATE="inventory.service.template"
TARGET="/etc/systemd/system/inventory.service"

if [ ! -f "$TEMPLATE" ]; then
    echo "❌ Template file $TEMPLATE not found in current directory!"
    exit 1
fi

sed "s|__WORKING_DIR__|$WORKING_DIR|g" "$TEMPLATE" > "$TARGET"

echo "📝 Service file created at $TARGET"

# 5. Reload and enable
systemctl daemon-reload
systemctl enable inventory.service

# 6. Ensure scripts are executable
chmod +x run_standalone.sh
chmod +x start_server.sh

echo ""
echo "🚀 TFM aInventory Standalone service installed and enabled!"
echo "   Commands:"
echo "   👉 sudo systemctl start inventory"
echo "   👉 sudo systemctl status inventory"
echo "   👉 sudo systemctl stop inventory"
echo ""
echo "Note: The service is currently ENABLED to start on boot, but NOT started."
echo "      Run 'sudo systemctl start inventory' to launch it now."
