#!/usr/bin/env bash

# Reload the *.yml config files
get_config_args() {
    find "${AM_CONFIG_PIPELINES}" -name '*.yml' -exec printf '\--config=%s ' {} \;
}

#
# Function that starts the daemon/service
#
do_start() {
    config=$(get_config_args)
    while true; do
        if [[ -z "$current_config" ]]; then
            shutdown_otel
            $DAEMON $config 2>> ${AM_HOME}/logs/otel-collector.err &
        elif [[ "$config" != "$current_config" ]]; then
            $DAEMON validate $current_config >> ${AM_HOME}/logs/otel-collector.err 2>&1
            if [[ $? -eq 0 ]]; then
                echo "$(date '+%Y-%m-%dT%H:%M:%S.%3N%z') info Detected new config: $current_config" >> ${AM_HOME}/logs/otel-collector.log
                shutdown_otel
                $DAEMON $current_config 2>> ${AM_HOME}/logs/otel-collector.err &
                config="$current_config"
            else
                echo "$(date '+%Y-%m-%dT%H:%M:%S.%3N%z') error The new config is invalid. So will not reload $current_config" >> ${AM_HOME}/logs/otel-collector.log
            fi
        fi
        current_config=$(get_config_args)
        sleep 60
    done &
    echo $! > $PIDFILE
}

#
# Function that stops the daemon/service
#
do_stop()
{
    shutdown_otel
    if [[ -f "$PIDFILE" ]]; then
        if pgrep -F $PIDFILE > /dev/null 2>&1; then # This will check the return code of the `pgrep` command
            PID=$(cat $PIDFILE)
            pkill -P $PID > /dev/null 2>&1 # kill other child processes
            kill -9 $PID > /dev/null 2>&1 && rm -f ${PIDFILE}
        fi
        rm -f ${PIDFILE}
    fi
}
#
# Function that sends a SIGHUP to the daemon/service
#
do_restart() {
    do_stop
    do_start
}
#
# Function that checks the running status of the daemon/service
#
check_status() {
    if [[ -f "$PIDFILE" ]]; then
        pgrep -F $PIDFILE
    else
        return 1
    fi
}
#
# Function that validates Otel Config
#
do_test() {
    $DAEMON $TEST_ARGS
}
