#!/bin/bash

# KNEL System Configuration Initializer
# Applies system-wide configuration files with conditional logic

set -euo pipefail

echo "Running system configuration initializer..."

# Create necessary directories
mkdir -p $ROOT_SSH_DIR

# Deploy system configuration files from copied templates
if [[ -f ./ZSH/tsys-zshrc ]]; then
    cp ./ZSH/tsys-zshrc /etc/zshrc
fi

if [[ -f ./SMTP/aliases ]]; then
    cp ./SMTP/aliases /etc/aliases
    newaliases
fi

if [[ -f ./Syslog/rsyslog.conf ]]; then
    cp ./Syslog/rsyslog.conf /etc/rsyslog.conf
fi

# Configure DHCP client
if [[ -f ./DHCP/dhclient.conf ]]; then
    cp ./DHCP/dhclient.conf /etc/dhcp/dhclient.conf
fi

# Configure SNMP
systemctl stop snmpd 2>/dev/null || true
/etc/init.d/snmpd stop 2>/dev/null || true

if [[ -f ./SNMP/snmp-sudo.conf ]]; then
    cp ./SNMP/snmp-sudo.conf /etc/sudoers.d/Debian-snmp
fi

# Adjust SNMP service for log verbosity
sed -i "s|-Lsd|-LS6d|" /lib/systemd/system/snmpd.service

# Configure SNMP based on system type (with pi-detect)
if command -v vcgencmd >/dev/null 2>&1; then
    export IS_RASPI="1"
else
    export IS_RASPI="0"
fi

if [[ $IS_RASPI -eq 1 ]] && [[ -f ./SNMP/snmpd-rpi.conf ]]; then
    cp ./SNMP/snmpd-rpi.conf /etc/snmp/snmpd.conf
elif [[ $IS_PHYSICAL_HOST -eq 1 ]] && [[ -f ./SNMP/snmpd-physicalhost.conf ]]; then
    cp ./SNMP/snmpd-physicalhost.conf /etc/snmp/snmpd.conf
elif [[ $IS_VIRT_GUEST -eq 1 ]] && [[ -f ./SNMP/snmpd.conf ]]; then
    cp ./SNMP/snmpd.conf /etc/snmp/snmpd.conf
fi

# Configure lldpd
if [[ -f ./NetworkDiscovery/lldpd ]]; then
    cp ./NetworkDiscovery/lldpd /etc/default/lldpd
    systemctl restart lldpd
fi

# Configure Cockpit
if [[ -f ./Cockpit/disallowed-users ]]; then
    cp ./Cockpit/disallowed-users /etc/cockpit/disallowed-users
    systemctl restart cockpit
fi

# Configure NTP for non-NTP servers
if [[ $NTP_SERVER_CHECK -eq 0 ]] && [[ -f ./NTP/ntp.conf ]]; then
    cp ./NTP/ntp.conf /etc/ntpsec/ntp.conf
    systemctl restart ntpsec.service
fi

# Always install rsyslog (removed librenms conditional)
DEBIAN_FRONTEND="noninteractive" apt-get -qq --yes -o Dpkg::Options::="--force-confold" install rsyslog
systemctl stop rsyslog
systemctl start rsyslog

# Reload systemd and restart SNMP
systemctl daemon-reload
systemctl restart snmpd 2>/dev/null || true
/etc/init.d/snmpd restart 2>/dev/null || true

# Performance tuning based on system type
if [[ $IS_PHYSICAL_HOST -gt 0 ]]; then
    cpufreq-set -r -g performance
    cpupower frequency-set --governor performance
fi

if [[ $IS_VIRT_GUEST -eq 1 ]]; then
    tuned-adm profile virtual-guest
fi

echo "System configuration initializer completed"