#!/bin/bash

# KNEL Wazuh Security Module
# Deploys and configures Wazuh security monitoring

set -euo pipefail

echo "Running Wazuh security module..."

# Check if this is the Wazuh server
export TSYS_NSM_CHECK="$(hostname | grep -c tsys-nsm || echo 0)"

if [[ $TSYS_NSM_CHECK -eq 0 ]]; then
    echo "Setting up Wazuh agent..."
    
    # Remove existing keyring if present
    if [[ -f /usr/share/keyrings/wazuh.gpg ]]; then
        rm -f /usr/share/keyrings/wazuh.gpg
    fi
    
    # Add Wazuh repository
    curl -s https://packages.wazuh.com/key/GPG-KEY-WAZUH | gpg --no-default-keyring --keyring gnupg-ring:/usr/share/keyrings/wazuh.gpg --import
    chmod 644 /usr/share/keyrings/wazuh.gpg
    echo "deb [signed-by=/usr/share/keyrings/wazuh.gpg] https://packages.wazuh.com/4.x/apt/ stable main" > /etc/apt/sources.list.d/wazuh.list
    
    # Install Wazuh agent
    apt-get update
    DEBIAN_FRONTEND="noninteractive" apt-get -y install wazuh-agent
    
    # Configure Wazuh agent
    if [[ -f ./configs/wazuh-agent.conf ]]; then
        cp ./configs/wazuh-agent.conf /var/ossec/etc/ossec.conf
    fi
    
    # Start and enable Wazuh agent
    systemctl daemon-reload
    systemctl enable wazuh-agent
    systemctl restart wazuh-agent
    
else
    echo "This is a Wazuh server, skipping agent setup"
fi

echo "Wazuh security module completed"