#!/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_startOtelCollector() {
    config=$(get_config_args)
    shutdown_otel
    $DAEMON $config 2>> ${AM_HOME}/logs/otel-collector.err &
    OTEL_PID=$!

    # Wait a moment for the process to start
    sleep 1

    if ps -p $OTEL_PID > /dev/null 2>&1; then
        echo "OtelCollector started with PID: $OTEL_PID"
    else
        echo "Error: OtelCollector failed to start"
        exit 1
    fi

    echo $OTEL_PID > $PIDFILE
}

#
# Function that stops the daemon/service
#
do_stopOtelCollector()
{
    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_restartOtelCollector() {
    do_stopOtelCollector
    do_startOtelCollector
}

check_both_status() {
    echo "Checking status of OtelCollector and DirectoryWatcher"
    
    # Determine PID file locations based on service installation status
    if isOtelCollectorServiceInstalled; then
        PIDFILE_BASE_DIR=/etc/otel-collector
    else
        PIDFILE_BASE_DIR=${AM_HOME}
    fi

    if isDirectoryWatcherServiceInstalled; then
        PIDFILE_DW_BASE_DIR=/etc/directory-watcher
    else
        PIDFILE_DW_BASE_DIR=${AM_HOME}
    fi

    # Set PID file paths
    PIDFILE=${PIDFILE_BASE_DIR}/am-agent.pid
    PIDFILE_DW=${PIDFILE_DW_BASE_DIR}/directory-watcher.pid

    # Check OTEL Collector status
    if [[ -f "$PIDFILE" ]]; then
        OTEL_PID=$(cat $PIDFILE)
        if [[ -n "$OTEL_PID" ]] && [[ "$OTEL_PID" =~ ^[0-9]+$ ]]; then
            if ps -p $OTEL_PID | grep otel-collector | grep -v grep > /dev/null 2>&1; then
                echo "OtelCollector is running with PID: $OTEL_PID"
            else
                echo "OtelCollector is not running"
            fi
        else
            echo "Invalid OTEL PID in $PIDFILE: '$OTEL_PID'"
        fi
    else
        echo "OTEL PID file not found at: $PIDFILE"
    fi

    # Check DirectoryWatcher status
    if [[ -f "$PIDFILE_DW" ]]; then
        DW_PID=$(cat $PIDFILE_DW)
        if [[ -n "$DW_PID" ]] && [[ "$DW_PID" =~ ^[0-9]+$ ]]; then
            if ps -p $DW_PID -o args= -ww | grep -q "com.mulesoft.dias.mule.agent.DirectoryWatcher" > /dev/null 2>&1; then
                echo "DirectoryWatcher is running with PID: $DW_PID"
            else
                echo "DirectoryWatcher is not running"
            fi
        else
            echo "Invalid DirectoryWatcher PID in $PIDFILE_DW: '$DW_PID'"
        fi
    else
        echo "DirectoryWatcher PID file not found at: $PIDFILE_DW"
    fi
}

#
# 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
}

startDirectoryWatcher() {
    # Check if Java is available in JAVA_HOME
    if [[ -z "$JAVA_HOME" ]]; then
        echo "Error: JAVA_HOME is not set"
        exit 1
    fi
    
    if [[ ! -x "$JAVA_HOME/bin/java" ]]; then
        echo "Error: Java is not available in JAVA_HOME: $JAVA_HOME"
        exit 1
    fi
    
    # Check Java version (optional but recommended)
    JAVA_VERSION=$("$JAVA_HOME/bin/java" -version 2>&1 | head -n 1 | cut -d'"' -f2)
    echo "Using Java version: $JAVA_VERSION from JAVA_HOME: $JAVA_HOME"
    
    # Determine execution context
    echo "Process execution mode - logging to files ${AM_HOME}/logs/directorywatcher.log and ${AM_HOME}/logs/directorywatcher.err"
    "$JAVA_HOME/bin/java" -D"muleHome=$HOME_DIR" -cp "${AM_HOME}/lib/*" com.mulesoft.dias.mule.agent.DirectoryWatcher >> "${AM_HOME}/logs/directorywatcher.log" 2>> "${AM_HOME}/logs/directorywatcher.err" &

    DW_PID=$!
    
    # Wait a moment for the process to start
    sleep 1
    
    # Verify the process is running
    if ps -p $DW_PID > /dev/null 2>&1; then
        echo "DirectoryWatcher started with PID: $DW_PID"
        echo $DW_PID > "${AM_HOME}/directory-watcher.pid"
    else
        echo "Error: DirectoryWatcher failed to start"
        exit 1
    fi
}

stopDirectoryWatcher() {
    PIDFILE_DW="${AM_HOME}/directory-watcher.pid"
    
    if [[ -f "$PIDFILE_DW" ]]; then
        PID=$(cat $PIDFILE_DW)
        if pgrep -F $PIDFILE_DW > /dev/null 2>&1; then
            kill -TERM $PID > /dev/null 2>&1
            sleep 2
            if pgrep -F $PIDFILE_DW > /dev/null 2>&1; then
                kill -KILL $PID > /dev/null 2>&1
            fi
        fi
        rm -f $PIDFILE_DW
    else
        echo "DirectoryWatcher PID file not found"
    fi
}
