#!/bin/bash
# GuruConnect Systemd Service Setup Script
# This script installs and enables the GuruConnect systemd service

set -e

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

echo "========================================="
echo "GuruConnect Systemd Service Setup"
echo "========================================="

# Check if running as root
if [ "$EUID" -ne 0 ]; then
    echo -e "${RED}ERROR: This script must be run as root (sudo)${NC}"
    exit 1
fi

# Paths
SERVICE_FILE="guruconnect.service"
SYSTEMD_DIR="/etc/systemd/system"
INSTALL_PATH="$SYSTEMD_DIR/guruconnect.service"

# Check if service file exists
if [ ! -f "$SERVICE_FILE" ]; then
    echo -e "${RED}ERROR: Service file not found: $SERVICE_FILE${NC}"
    echo "Make sure you're running this script from the server/ directory"
    exit 1
fi

# Stop existing service if running
if systemctl is-active --quiet guruconnect; then
    echo -e "${YELLOW}Stopping existing guruconnect service...${NC}"
    systemctl stop guruconnect
fi

# Copy service file
echo "Installing service file to $INSTALL_PATH..."
cp "$SERVICE_FILE" "$INSTALL_PATH"
chmod 644 "$INSTALL_PATH"

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

# Enable service (start on boot)
echo "Enabling guruconnect service..."
systemctl enable guruconnect

# Start service
echo "Starting guruconnect service..."
systemctl start guruconnect

# Wait a moment for service to start
sleep 2

# Check status
echo ""
echo "========================================="
echo "Service Status:"
echo "========================================="
systemctl status guruconnect --no-pager || true

echo ""
echo "========================================="
echo "Setup Complete!"
echo "========================================="
echo ""
echo "Useful commands:"
echo "  sudo systemctl status guruconnect   - Check service status"
echo "  sudo systemctl stop guruconnect     - Stop service"
echo "  sudo systemctl start guruconnect    - Start service"
echo "  sudo systemctl restart guruconnect  - Restart service"
echo "  sudo journalctl -u guruconnect -f   - View logs (follow)"
echo "  sudo journalctl -u guruconnect -n 100  - View last 100 log lines"
echo ""

# Final check
if systemctl is-active --quiet guruconnect; then
    echo -e "${GREEN}SUCCESS: GuruConnect service is running!${NC}"
    exit 0
else
    echo -e "${RED}WARNING: Service is not running. Check logs with: sudo journalctl -u guruconnect -n 50${NC}"
    exit 1
fi
