#!/usr/bin/env bash
RETVAL=0

MACHINE_TYPE=`uname -m`
if [ ${MACHINE_TYPE} == 'x86_64' ]; then
    # 64 bit otel-collector support will be added in later versions.
    DAEMON=${AM_HOME}/otel-collector/linux/32/otel-collector
else
    # Linux 32
    DAEMON=${AM_HOME}/otel-collector/linux/32/otel-collector
fi

if which dpkg > /dev/null 2> /dev/null
then
    . /lib/lsb/init-functions
    pidopts="-p $PIDFILE"
else
    # Source function library.
    . /etc/rc.d/init.d/functions
    # Determine if we can use the -p option to daemon, killproc, and status.
    # RHEL < 5 can't.
    if status | grep -q -- '-p' 2>/dev/null; then
        pidopts="-p $PIDFILE"
    fi
fi

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

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 &
    RETVAL=$?
    echo "$!" > $PIDFILE
    return $RETVAL
}

do_stop() {
    shutdown_otel # kill otel-collector to be safe
    if [[ -f "$PIDFILE" ]]; then
        if pgrep -F $PIDFILE > /dev/null 2>&1; then # This will check the return code of the `pgrep` command
            pgrep -P "$(head -n 1 $PIDFILE)" | xargs kill -9 # kill other child process
            killproc $pidopts $PIDFILE
            RETVAL=$?
            echo
            [ $RETVAL = 0 ] && rm -f ${PIDFILE}
        else
            rm -f ${PIDFILE}
        fi
    fi
}

do_restart() {
    do_stop
    if [ $? -ne 0 ]; then
        return 1
    fi
    do_start
}

check_status() {
    if [[ -f "$PIDFILE" ]]; then
        pgrep -F $PIDFILE
    else
        return 1
    fi
}

do_test() {
    $DAEMON $(get_config_args)
}
