#!/bin/bash
# RunSentry Agent Installation Script
# Handles complete installation including automatic registration if token provided
# Usage: RUNSENTRY_TOKEN=xxxx curl -fsSL https://runsentrystorage.blob.core.windows.net/main/install.sh | bash

set -e

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

# Configuration
INSTALL_DIR="/opt/runsentry"
VENV_DIR="${INSTALL_DIR}/venv"
CONFIG_DIR="/etc/runsentry"
SERVICE_FILE="/etc/systemd/system/runsentry-agent.service"

# Check if running as root
if [ "$EUID" -ne 0 ]; then
    echo -e "${RED}Error: This script must be run as root${NC}" >&2
    exit 1
fi

# Detect OS
OS="$(uname -s)"
if [ "$OS" != "Linux" ]; then
    echo -e "${RED}Error: Unsupported OS: $OS. Linux is required.${NC}" >&2
    exit 1
fi

echo -e "${GREEN}RunSentry Agent Installation${NC}"
echo "================================"

# Check Python 3.10+
echo "Checking Python version..."
if ! command -v python3 &> /dev/null; then
    echo -e "${RED}Error: Python 3 is not installed${NC}" >&2
    exit 1
fi

PYTHON_VERSION=$(python3 -c 'import sys; print(".".join(map(str, sys.version_info[:2])))')
PYTHON_MAJOR=$(echo $PYTHON_VERSION | cut -d. -f1)
PYTHON_MINOR=$(echo $PYTHON_VERSION | cut -d. -f2)

if [ "$PYTHON_MAJOR" -lt 3 ] || ([ "$PYTHON_MAJOR" -eq 3 ] && [ "$PYTHON_MINOR" -lt 10 ]); then
    echo -e "${RED}Error: Python 3.10+ is required. Found: $PYTHON_VERSION${NC}" >&2
    exit 1
fi

echo -e "${GREEN}Python $PYTHON_VERSION found${NC}"

# Create installation directories (idempotent)
echo "Creating installation directories..."
mkdir -p "$INSTALL_DIR"
mkdir -p "$CONFIG_DIR"
mkdir -p "$(dirname "$SERVICE_FILE")"

# Create virtual environment (idempotent - only create if doesn't exist)
echo "Setting up virtual environment..."
if [ ! -d "$VENV_DIR" ]; then
    echo "Creating new virtual environment..."
    python3 -m venv "$VENV_DIR"
else
    echo "Virtual environment already exists, skipping creation..."
fi

# Activate virtual environment and install/upgrade agent
echo "Installing RunSentry agent package..."
source "$VENV_DIR/bin/activate"
pip install --upgrade pip --quiet
pip install --upgrade runsentry-agent --quiet

# Verify installation by checking runsentry command exists
if [ ! -f "$VENV_DIR/bin/runsentry" ]; then
    echo -e "${RED}Error: Installation verification failed${NC}" >&2
    exit 1
fi

INSTALLED_VERSION=$("$VENV_DIR/bin/runsentry" --version 2>/dev/null || echo "installed")
echo -e "${GREEN}RunSentry agent installed successfully (version: $INSTALLED_VERSION)${NC}"

# Create/update systemd service file
echo "Installing systemd service..."
cat > "$SERVICE_FILE" <<EOF
[Unit]
Description=RunSentry Agent
After=network.target

[Service]
Type=simple
ExecStart=$VENV_DIR/bin/runsentry daemon
Restart=always
RestartSec=10
User=root
StandardOutput=journal
StandardError=journal

[Install]
WantedBy=multi-user.target
EOF

# Reload systemd and enable service (idempotent)
echo "Enabling systemd service..."
systemctl daemon-reload
systemctl enable runsentry-agent.service >/dev/null 2>&1 || true

# Automatic registration if token is provided
if [ -n "$RUNSENTRY_TOKEN" ]; then
    echo ""
    echo "Registering agent with RunSentry backend..."
    
    BACKEND_URL="${RUNSENTRY_BACKEND_URL:-https://runsentry-api.azurewebsites.net/}"
    AGENT_NAME="${RUNSENTRY_AGENT_NAME:-$(hostname)}"
    
    if "$VENV_DIR/bin/runsentry" register \
        --token "$RUNSENTRY_TOKEN" \
        --backend-url "$BACKEND_URL" \
        --agent-name "$AGENT_NAME"; then
        echo -e "${GREEN}✓ Agent registered successfully${NC}"
        
        # Start the service if registration succeeded
        echo "Starting runsentry-agent service..."
        if systemctl start runsentry-agent.service 2>/dev/null; then
            echo -e "${GREEN}✓ Service started successfully${NC}"
        else
            echo -e "${YELLOW}Warning: Service installed but failed to start. Check logs with: journalctl -u runsentry-agent${NC}" >&2
        fi
    else
        echo -e "${YELLOW}Warning: Registration failed. You can register manually later with:${NC}" >&2
        echo "  RUNSENTRY_TOKEN=xxx $VENV_DIR/bin/runsentry register" >&2
        echo "" >&2
        echo "Service is installed but not started. Start it manually after registration:" >&2
        echo "  systemctl start runsentry-agent" >&2
    fi
else
    echo ""
    echo -e "${YELLOW}Note: No RUNSENTRY_TOKEN provided. Registration skipped.${NC}"
    echo "To register and start the agent, run:"
    echo "  RUNSENTRY_TOKEN=xxx $VENV_DIR/bin/runsentry register --backend-url https://runsentry-api.azurewebsites.net/"
    echo "  systemctl start runsentry-agent"
fi

echo ""
echo -e "${GREEN}Installation complete!${NC}"
echo ""
echo "Service management:"
echo "  Status:  systemctl status runsentry-agent"
echo "  Logs:    journalctl -u runsentry-agent -f"
echo "  Restart: systemctl restart runsentry-agent"
echo ""

