#!/bin/sh

ossec_type="%%OSSEC_TYPE%%"
ossec_home="%%OSSEC_HOME%%"

agent_conf_dir="${ossec_home}/etc/agent.conf.d"
agent_conf_files="${agent_conf_dir}/*.conf"

select_elements() {
    local element="$1"
    sed -En "/<${element}.*>/,/<\/${element}>/p"
}

remove_comments() {
    # Comments must be on separate lines i.e. not next to uncommented code
    awk '/<!--/ {off=1} /-->/ {off=2} /([\s\S]*)/ {if (off==0) print; if (off==2) off=0}'
}

remove_empty_lines() {
    sed -E '/^[[:space:]]*$/d'
}

agent_conf() {

    echo "<!-- OSSEC HIDS %%VERSION%% -->"
    echo
    echo "<!-- DO NOT EDIT - file generated automatically - edit \"agent.conf.d/900.local.conf\" instead -->"
    echo

    cat $@ | remove_comments | select_elements "agent_config" | remove_empty_lines
}

agent_conf "${agent_conf_files}"
