#!/bin/bash

# C-Relay Systemd Service Installation Script
# This script installs the C-Relay as a systemd service

set -e

# Configuration
INSTALL_DIR="/opt/c-relay"
SERVICE_NAME="c-relay"
SERVICE_FILE="c-relay.service"
BINARY_NAME="c_relay_x86"

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

echo -e "${GREEN}=== C-Relay Systemd Service Installation ===${NC}"

# Check if running as root
if [[ $EUID -ne 0 ]]; then
   echo -e "${RED}Error: This script must be run as root${NC}"
   echo "Usage: sudo ./install-systemd.sh"
   exit 1
fi

# Check if binary exists (script is in systemd/ subdirectory)
if [ ! -f "../build/$BINARY_NAME" ]; then
    echo -e "${RED}Error: Binary ../build/$BINARY_NAME not found${NC}"
    echo "Please run 'make' from the project root directory first"
    exit 1
fi

# Check if service file exists
if [ ! -f "$SERVICE_FILE" ]; then
    echo -e "${RED}Error: Service file $SERVICE_FILE not found${NC}"
    exit 1
fi

# Create c-relay user if it doesn't exist
if ! id "c-relay" &>/dev/null; then
    echo -e "${YELLOW}Creating c-relay user...${NC}"
    useradd --system --shell /bin/false --home-dir $INSTALL_DIR --create-home c-relay
else
    echo -e "${GREEN}User c-relay already exists${NC}"
fi

# Create installation directory
echo -e "${YELLOW}Creating installation directory...${NC}"
mkdir -p $INSTALL_DIR
mkdir -p $INSTALL_DIR/db

# Copy binary
echo -e "${YELLOW}Installing binary...${NC}"
cp ../build/$BINARY_NAME $INSTALL_DIR/
chmod +x $INSTALL_DIR/$BINARY_NAME

# Set permissions
echo -e "${YELLOW}Setting permissions...${NC}"
chown -R c-relay:c-relay $INSTALL_DIR

# Install systemd service
echo -e "${YELLOW}Installing systemd service...${NC}"
cp $SERVICE_FILE /etc/systemd/system/
systemctl daemon-reload

# Enable service
echo -e "${YELLOW}Enabling service...${NC}"
systemctl enable $SERVICE_NAME

echo -e "${GREEN}=== Installation Complete ===${NC}"
echo
echo -e "${GREEN}Next steps:${NC}"
echo "1. Configure environment variables in /etc/systemd/system/$SERVICE_FILE if needed"
echo "2. Start the service: sudo systemctl start $SERVICE_NAME"
echo "3. Check status: sudo systemctl status $SERVICE_NAME"
echo "4. View logs: sudo journalctl -u $SERVICE_NAME -f"
echo
echo -e "${GREEN}Service commands:${NC}"
echo "  Start:   sudo systemctl start $SERVICE_NAME"
echo "  Stop:    sudo systemctl stop $SERVICE_NAME"
echo "  Restart: sudo systemctl restart $SERVICE_NAME"
echo "  Status:  sudo systemctl status $SERVICE_NAME"
echo "  Logs:    sudo journalctl -u $SERVICE_NAME"
echo
echo -e "${GREEN}Installation directory: $INSTALL_DIR${NC}"
echo -e "${GREEN}Service file: /etc/systemd/system/$SERVICE_FILE${NC}"
echo
echo -e "${YELLOW}Note: The relay will run on port 8888 by default${NC}"
echo -e "${YELLOW}Database will be created automatically in $INSTALL_DIR/db/${NC}"