#!/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

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

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
start() {
    restart
}

# Stop function
stop() {
    do_stop
}

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

    do_restart
}

case "$ACTION" in
    start)
        echo $STARTING_OTEL_COLLECTOR
        if isServiceInstalled; then
            if [[ "$IS_SERVICE" = true ]]; then
                start
                echo $OTEL_COLLECTOR_STARTED
            else
                echo ${AM_SERVICE_INSTALLED}
            fi
        else
            start
            if [[ -f "$PIDFILE" ]]; then
                echo "${OTEL_COLLECTOR_STARTED}"
                echo "PID: $(cat $PIDFILE)"
            fi
        fi
    ;;
    stop)
        if [[ -f "$PIDFILE" ]]; then
            echo $STOPPING_OTEL_COLLECTOR
            stop
            echo "${OTEL_COLLECTOR_STOPPED}"
        fi
    ;;
    restart)
        echo $RESTARTING_OTEL_COLLECTOR
        if isServiceInstalled; then
            if [[ "$IS_SERVICE" = true ]]; then
                restart
                echo $OTEL_COLLECTOR_STARTED
            else
                echo ${AM_SERVICE_INSTALLED}
            fi
        else
            restart
        fi
    ;;
    *)
        echo "Usage: $0 [actions] [options]"
        echo " "
        echo "[actions]:"
        echo "start,    Start otel-collector"
        echo "stop,     Stop otel-collector"
        echo "restart,  Restart otel-collector"
        echo " "
        echo "[options]:"
        echo "-m,       Override Home directory"
        echo " "
        echo "DESCRIPTION: Run Anypoint Monitoring OpenTelemetry Collector"
        exit 0
        ;;
esac

exit 0
