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

MACHINE_TYPE=`uname -m`

# TODO: Add support for 64bit OTEL Collector in future versions
#  when available using the check ${MACHINE_TYPE} == 'x86_64'

OTEL_COLLECTOR_BINARY=${AM_HOME}/otel-collector/linux/32/otel-collector

USE_PORTABLE_FUNCS=0

if which dpkg > /dev/null 2> /dev/null
then
    . /lib/lsb/init-functions
    pidopts="-p $PIDFILE"
else
    if [ -f /etc/rc.d/init.d/functions ]; then
        # 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
    else
        USE_PORTABLE_FUNCS=1
    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
            $OTEL_COLLECTOR_BINARY $config 2>> ${AM_HOME}/logs/otel-collector.err &
        elif [[ "$config" != "$current_config" ]]; then
            $OTEL_COLLECTOR_BINARY 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
                $OTEL_COLLECTOR_BINARY $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
            if [[ $USE_PORTABLE_FUNCS -eq 1 ]]; then
                kill_process_by_pidfile "$PIDFILE"
            else
                killproc $pidopts $PIDFILE
            fi
            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() {
    $OTEL_COLLECTOR_BINARY $(get_config_args)
}

# Portable replacement for killproc
# Using kill -0 to check if kill has the permission to kill the process
# https://unix.stackexchange.com/a/169899  
kill_process_by_pidfile() {
    local pidfile="$1"
    if [[ -f "$pidfile" ]]; then
        local pid
        pid=$(head -n 1 "$pidfile")
        if kill -0 "$pid" 2>/dev/null; then
            kill "$pid"
            sleep 2
            if kill -0 "$pid" 2>/dev/null; then
                kill -9 "$pid"
            fi
            echo "Killed process $pid"
        else
            echo "No running process with PID $pid"
        fi
        rm -f "$pidfile"
    else
        echo "PID file $pidfile does not exist"
    fi
}