#!/bin/bash

# KNEL OAM Initializer
# Sets up Operations and Maintenance tools including LibreNMS monitoring agents

set -euo pipefail

echo "Running OAM initializer..."

# Setup up2date script
if [[ -f ./scripts/up2date.sh ]]; then
    cp ./scripts/up2date.sh /usr/local/bin/up2date.sh
    chmod +x /usr/local/bin/up2date.sh
fi

# Deploy LibreNMS check_mk agent
if [[ -f ./librenms/check_mk_agent ]]; then
    # Create agent directories
    mkdir -p /usr/lib/check_mk_agent/plugins
    mkdir -p /usr/lib/check_mk_agent/local
    mkdir -p /etc/check_mk
    mkdir -p /var/lib/check_mk_agent
    
    # Deploy main agent
    cp ./librenms/check_mk_agent /usr/bin/check_mk_agent
    chmod +x /usr/bin/check_mk_agent
    
    # Deploy distro script for OS detection
    if [[ -f ./librenms/distro ]]; then
        cp ./librenms/distro /usr/bin/distro
        chmod +x /usr/bin/distro
    fi
    
    # Deploy systemd service files
    if [[ -f ./librenms/check_mk.socket ]]; then
        cp ./librenms/check_mk.socket /etc/systemd/system/check_mk.socket
    fi
    
    if [[ -f ./librenms/check_mk@.service ]]; then
        cp ./librenms/check_mk@.service /etc/systemd/system/check_mk@.service
    fi
    
    # Deploy plugins
    for plugin in ./librenms/*.sh ./librenms/*.py; do
        if [[ -f "$plugin" ]]; then
            plugin_name=$(basename "$plugin")
            cp "$plugin" /usr/lib/check_mk_agent/plugins/
            chmod +x "/usr/lib/check_mk_agent/plugins/$plugin_name"
        fi
    done
    
    # Deploy other plugins (without extensions)
    for plugin in ./librenms/smart ./librenms/ntp-client ./librenms/ntp-server.sh \
                  ./librenms/os-updates.sh ./librenms/postfix-queues ./librenms/postfixdetailed \
                  ./librenms/ups-nut.sh; do
        if [[ -f "$plugin" ]]; then
            plugin_name=$(basename "$plugin")
            cp "$plugin" /usr/lib/check_mk_agent/plugins/
            chmod +x "/usr/lib/check_mk_agent/plugins/$plugin_name"
        fi
    done
    
    # Deploy smart config if present
    if [[ -f ./librenms/smart.config ]]; then
        cp ./librenms/smart.config /etc/check_mk/smart.config
    fi
    
    # Reload systemd and enable check_mk socket
    systemctl daemon-reload
    systemctl enable check_mk.socket
    systemctl start check_mk.socket
    
    echo "LibreNMS agent deployed and enabled"
fi

echo "OAM initializer completed"