#!/bin/bash

# Setup script for absRecommend systemd service
# This script installs and configures the service to run on boot with auto-restart

set -e  # Exit on error

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
SERVICE_FILE="$SCRIPT_DIR/absrecommend.service"
SERVICE_NAME="absrecommend"

echo "========================================="
echo "absRecommend Service Setup"
echo "========================================="
echo ""

# Check if running as root
if [ "$EUID" -eq 0 ]; then
    echo "ERROR: Please run this script as a regular user (not root/sudo)"
    echo "The script will prompt for sudo password when needed"
    exit 1
fi

# Check if service file exists
if [ ! -f "$SERVICE_FILE" ]; then
    echo "ERROR: Service file not found at $SERVICE_FILE"
    exit 1
fi

# Stop any existing background processes
echo "Stopping any running instances..."
pkill -f "python.*main.py" || true
sleep 2

# Copy service file
echo "Installing service file..."
sudo cp "$SERVICE_FILE" /etc/systemd/system/

# Reload systemd
echo "Reloading systemd..."
sudo systemctl daemon-reload

# Enable service
echo "Enabling service to start on boot..."
sudo systemctl enable $SERVICE_NAME

# Start service
echo "Starting service..."
sudo systemctl start $SERVICE_NAME

# Wait a moment for service to start
sleep 2

# Check status
echo ""
echo "========================================="
echo "Service Status:"
echo "========================================="
sudo systemctl status $SERVICE_NAME --no-pager || true

echo ""
echo "========================================="
echo "Setup Complete!"
echo "========================================="
echo ""
echo "The service is now running and will:"
echo "  - Start automatically on system boot"
echo "  - Restart automatically if it crashes"
echo "  - Wait 5 seconds between restart attempts"
echo ""
echo "Useful commands:"
echo "  View logs:       sudo journalctl -u $SERVICE_NAME -f"
echo "  Restart:         sudo systemctl restart $SERVICE_NAME"
echo "  Stop:            sudo systemctl stop $SERVICE_NAME"
echo "  Start:           sudo systemctl start $SERVICE_NAME"
echo "  Status:          sudo systemctl status $SERVICE_NAME"
echo "  Disable startup: sudo systemctl disable $SERVICE_NAME"
echo ""
echo "Application running at: http://0.0.0.0:8000"
echo ""
