#!/bin/bash

# Claude Code Router systemd installation script

set -e

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

# Check if running as root
if [ "$EUID" -ne 0 ]; then 
    echo -e "${RED}Please run this script as root (use sudo)${NC}"
    exit 1
fi

echo -e "${GREEN}Installing Claude Code Router as systemd service...${NC}"

# Variables
SERVICE_NAME="claude-code-router"
SERVICE_FILE="/etc/systemd/system/${SERVICE_NAME}.service"
INSTALL_DIR="/opt/claude-code-router"
CURRENT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"

# Create installation directory
echo "Creating installation directory..."
mkdir -p ${INSTALL_DIR}

# Copy files
echo "Copying files..."
cp -r ${CURRENT_DIR}/dist ${INSTALL_DIR}/
cp ${CURRENT_DIR}/package.json ${INSTALL_DIR}/
cp -r ${CURRENT_DIR}/node_modules ${INSTALL_DIR}/

# Create logs directory
mkdir -p ${INSTALL_DIR}/logs

# Create service file
echo "Creating systemd service file..."
cat > ${SERVICE_FILE} << EOF
[Unit]
Description=Claude Code Router - Routes Claude Code requests to different LLM providers
Documentation=https://github.com/yourusername/claude-code-router
After=network.target

[Service]
Type=simple
User=$(logname)
WorkingDirectory=${INSTALL_DIR}
ExecStart=/usr/bin/node ${INSTALL_DIR}/dist/index.js start
Restart=always
RestartSec=5

# Resource limits
MemoryLimit=512M
CPUQuota=80%

# Environment
Environment="NODE_ENV=production"
Environment="SERVICE_PORT=3456"
Environment="HOME=/home/$(logname)"

# Security
NoNewPrivileges=true
PrivateTmp=true

# Logging
StandardOutput=journal
StandardError=journal
SyslogIdentifier=claude-code-router

# Graceful shutdown
KillMode=mixed
KillSignal=SIGTERM
TimeoutStopSec=30

[Install]
WantedBy=multi-user.target
EOF

# Set permissions
chown -R $(logname):$(logname) ${INSTALL_DIR}

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

# Enable service
echo "Enabling service..."
systemctl enable ${SERVICE_NAME}

echo -e "${GREEN}Installation complete!${NC}"
echo
echo "To manage the service, use:"
echo "  sudo systemctl start ${SERVICE_NAME}    # Start the service"
echo "  sudo systemctl stop ${SERVICE_NAME}     # Stop the service"
echo "  sudo systemctl restart ${SERVICE_NAME}  # Restart the service"
echo "  sudo systemctl status ${SERVICE_NAME}   # Check service status"
echo "  sudo journalctl -u ${SERVICE_NAME} -f   # View logs"
echo
echo "Or continue using the CLI commands:"
echo "  ccr start    # Start the service"
echo "  ccr stop     # Stop the service"
echo "  ccr status   # Check status"