#!/usr/bin/env bash
IS_SERVICE=false
ACTION=$1
shift $((OPTIND))
while getopts sm:  option
do
case "${option}"
in
m) HOME_DIR=${OPTARG};;
s) IS_SERVICE=true;;
esac
done

if [[ ! -d "$HOME_DIR" ]]; then
	if [[ -d "$MULE_HOME" ]]; then
		HOME_DIR=${MULE_HOME}
	else
	    cd $(dirname $0)
        cd ../..
        HOME_DIR=`pwd`
	fi
fi

# Detect JAVA_HOME if not provided by user
if [[ -z "$JAVA_HOME" ]]; then
    # Try to find Java in common locations
    if command -v java >/dev/null 2>&1; then
        # Java is in PATH, find its installation directory
        JAVA_PATH=$(which java)
        if [[ -L "$JAVA_PATH" ]]; then
            # Resolve symlink
            JAVA_PATH=$(readlink -f "$JAVA_PATH")
        fi
        # Go up two directories from bin/java to get JAVA_HOME
        JAVA_HOME=$(dirname "$(dirname "$JAVA_PATH")")
        echo "Auto-detected JAVA_HOME: $JAVA_HOME"
    else
        echo "Warning: Could not auto-detect JAVA_HOME. Please set JAVA_HOME environment variable."
        echo "Example: export JAVA_HOME=/path/to/java/home"
        JAVA_HOME=""
        exit 1
    fi
else
    echo "Using user-provided JAVA_HOME: $JAVA_HOME"
fi

# Export variables so the sub program can use them
export PATH=/usr/bin:/sbin:/bin:/usr/sbin
export AM_HOME=${HOME_DIR}/am
export AM_CONFIG=${AM_HOME}/config
export AM_CONFIG_PIPELINES=${AM_HOME}/config/pipelines
export GOMEMLIMIT=26MiB
source ${AM_HOME}/bin/tools/serviceHelper
source ${AM_HOME}/bin/tools/message


if [[ "$IS_SERVICE" = true ]]; then
	export OTEL_COLLECTOR_DATA=/var/lib/otel-collector
	export OTEL_COLLECTOR_LOGS=/var/log/otel-collector
	export PIDFILE_BASE_DIR=/etc/otel-collector
	export PIDFILE_DW_BASE_DIR=/etc/directory-watcher
else
	export OTEL_COLLECTOR_DATA=${HOME_DIR}/.mule/.am/otel-collector/data
	export OTEL_COLLECTOR_LOGS=${AM_HOME}/logs
	export PIDFILE_BASE_DIR=${AM_HOME}
	export PIDFILE_DW_BASE_DIR=${AM_HOME}
fi

mkdir -p ${OTEL_COLLECTOR_DATA} ${OTEL_COLLECTOR_LOGS} ${PIDFILE_BASE_DIR}

shutdown_otel() {
    process_name="otel-collector"
    timeout=60  # Timeout in seconds to wait for graceful shutdown

    # Send the graceful termination signal
    pkill -SIGTERM "$process_name"

    # Wait for the process to stop completely, with a timeout
    for (( i=0; i<timeout; i++ )); do
        if ! pgrep "$process_name" > /dev/null; then
            break
        fi
        sleep 1
    done

    # If the process did not stop after the timeout, you may want to forcefully kill it
    if pgrep "$process_name" > /dev/null; then
#        echo "$process_name did not stop within $timeout seconds. Forcing termination."
        pkill -SIGKILL "$process_name"
    fi
}

PIDFILE=${PIDFILE_BASE_DIR}/am-agent.pid
PIDFILE_DW=${PIDFILE_DW_BASE_DIR}/directory-watcher.pid

if [[ "$OSTYPE" == "darwin"* ]]; then
    # OSX
    chmod +x ${AM_HOME}/otel-collector/osx/otel-collector
    DAEMON=${AM_HOME}/otel-collector/osx/otel-collector
    source ${AM_HOME}/bin/tools/tool-osx
else
    source ${AM_HOME}/bin/tools/tool-linux
fi

# Start function
startOtelCollector() {
    restartOtelCollector
}

# Stop function
stopOtelCollector() {
    do_stopOtelCollector
}

# Restart function - Stops and starts the service
restartOtelCollector() {
    # Set default values for resiliency.
    export ENV_NAME=${ENV_NAME:-prod}
    export OTEL_RECEIVER_PROMETHEUS_INTERVAL=${OTEL_RECEIVER_PROMETHEUS_INTERVAL:-1m}

    do_restartOtelCollector
}

case "$ACTION" in
    start)
        echo $STARTING_OTEL_COLLECTOR
        if isOtelCollectorServiceInstalled && isDirectoryWatcherServiceInstalled; then
            # start both otel collector and directory watcher in service mode
            ${AM_HOME}/bin/am-service start
            echo $OTEL_COLLECTOR_STARTED
        else
            startOtelCollector
            if [[ -f "$PIDFILE" ]]; then
                echo "${OTEL_COLLECTOR_STARTED}"
                echo "PID: $(cat $PIDFILE)"
            fi
            startDirectoryWatcher
            if [[ -f "$PIDFILE_DW" ]]; then
                echo "${DIR_WATCHER_STARTED}"
                echo "PID: $(cat $PIDFILE_DW)"
            fi
        fi
    ;;
    stop)
        if isOtelCollectorServiceInstalled && isDirectoryWatcherServiceInstalled; then
            # stop both otel collector and directory watcher in service mode
            ${AM_HOME}/bin/am-service stop
            echo $OTEL_COLLECTOR_STOPPED
            echo $DIR_WATCHER_STOPPED
        else
            if [[ -f "$PIDFILE" ]]; then
                echo $STOPPING_OTEL_COLLECTOR
                stopOtelCollector
                echo "${OTEL_COLLECTOR_STOPPED}"
            fi
            if [[ -f "$PIDFILE_DW" ]]; then
                echo $STOPPING_DIR_WATCHER
                stopDirectoryWatcher
                echo "${DIR_WATCHER_STOPPED}"
            fi
        fi
    ;;
    restart)
        echo $RESTARTING_OTEL_COLLECTOR
        if isOtelCollectorServiceInstalled && isDirectoryWatcherServiceInstalled; then
            # restart both otel collector and directory watcher in service mode
            ${AM_HOME}/bin/am-service restart
            echo $OTEL_COLLECTOR_STARTED
            echo $DIR_WATCHER_STARTED
        else
            restartOtelCollector
            stopDirectoryWatcher
            startDirectoryWatcher
        fi
    ;;
    
    start-otel)
        echo $STARTING_OTEL_COLLECTOR
        startOtelCollector
    ;;

    stop-otel)
        echo $STOPPING_OTEL_COLLECTOR
        stopOtelCollector
    ;;

    restart-otel)
        echo $RESTARTING_OTEL_COLLECTOR
        restartOtelCollector
    ;;

    start-dw)
        echo $STARTING_DIR_WATCHER
        startDirectoryWatcher
    ;;
    stop-dw)
        echo $STOPPING_DIR_WATCHER
        stopDirectoryWatcher
    ;;
    restart-dw)
        echo $RESTARTING_DIR_WATCHER
        stopDirectoryWatcher
        startDirectoryWatcher
    ;;
    status)
        check_both_status
    ;;

    *)
        echo "Usage: $0 [actions] [options]"
        echo " "
        echo "[actions]:"
        echo "start,        Start otel-collector and directory watcher"
        echo "stop,         Stop otel-collector and directory watcher"
        echo "restart,      Restart otel-collector and directory watcher"
        echo "start-otel,   Start otel-collector"
        echo "stop-otel,    Stop otel-collector"
        echo "restart-otel, Restart otel-collector"
        echo "start-dw,     Start directory watcher"
        echo "stop-dw,      Stop directory watcher"
        echo "restart-dw,   Restart directory watcher"
        echo " "
        echo "[options]:"
        echo "-m,       Override Home directory"
        echo " "
        echo "DESCRIPTION: Run Anypoint Monitoring OpenTelemetry Collector"
        exit 0
        ;;
esac

exit 0
