#!/usr/bin/env bash
# ********* Starting configuration *********
while getopts m:h  option
do
case "${option}"
in
m) HOME_DIR=${OPTARG};;
h)
    echo "DESCRIPTION: Install Anypoint Monitoring OpenTelemetry Collector"
    echo "Usage: $0 [options]"
    echo " "
    echo "options:"
    echo "-h,       show help"
    echo "-m,       set home directory - defaults to MULE_HOME"
    echo " "
    exit 0
    ;;
esac
done

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

echo "MULE_HOME is set to ${HOME_DIR}"

AM_HOME=${HOME_DIR}/am
source ${AM_HOME}/bin/tools/serviceHelper
INSTALLATION_NAME_FILE="${AM_HOME}/config/installation.name"
# Load persisted name (if any); this determines prefixed unit/pid names for this AM_HOME
if [[ -f "$INSTALLATION_NAME_FILE" ]]; then
    INSTALLATION_NAME="$(cat "$INSTALLATION_NAME_FILE" 2>/dev/null | tr -d '[:space:]')"
fi
NAME_PREFIX=""
if [[ -n "$INSTALLATION_NAME" ]]; then
    NAME_PREFIX="${INSTALLATION_NAME}-"
fi

if [[ "$OSTYPE" == "darwin"* ]]; then
    source ${AM_HOME}/bin/tools/tool-osx
else
    source ${AM_HOME}/bin/tools/tool-linux
fi

check_both_status

echo "Clearing artifacts..."
rm -fr ${AM_HOME}/config/prospectors
rm -fr ${AM_HOME}/config/certs
rm -f ${AM_HOME}/config/proxy.url
rm -f ${AM_HOME}/config/telemetry.port
rm -f ${AM_HOME}/config/telemetry.logs.level
rm -f ${AM_HOME}/config/telemetry.logs.output.path
rm -f ${AM_HOME}/config/telemetry.logs.error.path
rm -f ${HOME_DIR}/server-plugins/mule-agent-plugin/lib/mule-agent-dias-*.jar 1> /dev/null 2>&1
rm -f ${HOME_DIR}/server-plugins/mule-agent-plugin/lib/analytics-metrics-collector-*.jar 1> /dev/null 2>&1
rm -f ${HOME_DIR}/server-plugins/mule-agent-plugin/lib/modules/mule-agent-dias-*.jar 1> /dev/null 2>&1
rm -f ${HOME_DIR}/server-plugins/mule-agent-plugin/lib/modules/analytics-metrics-collector-*.jar 1> /dev/null 2>&1
rm -f ${HOME_DIR}/plugins/mule-agent-plugin/lib/modules/mule-agent-dias-*.jar 1> /dev/null 2>&1
rm -f ${HOME_DIR}/plugins/mule-agent-plugin/lib/modules/analytics-metrics-collector-*.jar 1> /dev/null 2>&1

# Print the MULE_HOME referenced inside a systemd unit file (if present)
print_unit_mule_home() {
    UNIT_FILE="$1"
    PRINT_IF_UNDETERMINED="$2" # "true" to emit not-determined message on failure; otherwise silent
    if [[ -f "$UNIT_FILE" ]]; then
        # Try Environment=MULE_HOME first
        MULE_HOME_IN_UNIT="$(grep -E '^Environment=MULE_HOME=' "$UNIT_FILE" 2>/dev/null | head -n1 | cut -d'=' -f2-)"
        if [[ -z "$MULE_HOME_IN_UNIT" ]]; then
            # Fallback: parse ExecStart path like: /bin/bash <MULE_HOME>/am/bin/am start-otel -s
            MULE_HOME_IN_UNIT="$(grep -E '^ExecStart=' "$UNIT_FILE" 2>/dev/null | head -n1 | sed -E 's#^ExecStart=.* (/[^ ]*)/am/bin/am .*#\1#')"
        fi
        if [[ -n "$MULE_HOME_IN_UNIT" ]]; then
            echo "Systemd unit '$(basename "$UNIT_FILE")' targets MULE_HOME: ${MULE_HOME_IN_UNIT}"
            return 0
        else
            if [[ "$PRINT_IF_UNDETERMINED" == "true" ]]; then
                echo "Systemd unit '$(basename "$UNIT_FILE")': MULE_HOME could not be determined"
            fi
            return 1
        fi
    else
        return 1
    fi
}

if isOtelCollectorServiceInstalled; then
    echo "Stopping OtelCollector and DirectoryWatcher service..."
    INSTALLATION_NAME="$INSTALLATION_NAME" ${AM_HOME}/bin/am-service stop
    INSTALLATION_NAME="$INSTALLATION_NAME" ${AM_HOME}/bin/am-service disable
    echo "Removing OtelCollector and DirectoryWatcher service files..."
    # Show which MULE_HOME each unit targets before removal
    _unit="${NAME_PREFIX}am-otel-collector.service"
    if ! print_unit_mule_home "/lib/systemd/system/${_unit}" "false"; then
        print_unit_mule_home "/usr/lib/systemd/system/${_unit}" "true"
    fi
    _unit="${NAME_PREFIX}am-directory-watcher.service"
    if ! print_unit_mule_home "/lib/systemd/system/${_unit}" "false"; then
        print_unit_mule_home "/usr/lib/systemd/system/${_unit}" "true"
    fi
    run_as_root rm -f "/lib/systemd/system/${NAME_PREFIX}am-otel-collector.service"
    run_as_root rm -f "/lib/systemd/system/${NAME_PREFIX}am-directory-watcher.service"
    # Some distros install units under /usr/lib/systemd/system
    run_as_root rm -f "/usr/lib/systemd/system/${NAME_PREFIX}am-otel-collector.service"
    run_as_root rm -f "/usr/lib/systemd/system/${NAME_PREFIX}am-directory-watcher.service"
    echo "Removing OtelCollector and DirectoryWatcher PID files..."
    run_as_root rm -f "/etc/otel-collector/${NAME_PREFIX}am-agent.pid"
    run_as_root rm -f "/etc/directory-watcher/${NAME_PREFIX}directory-watcher.pid"
    echo "Reloading systemd services..."
    run_as_root systemctl daemon-reload
    run_as_root systemctl reset-failed
else
    echo "Stopping OtelCollector process..."
    ${AM_HOME}/bin/am stop
    echo "Removing OtelCollector PID file..."
    rm -f "${AM_HOME}/${NAME_PREFIX}am-agent.pid" || true
   
    # Stop DirectoryWatcher process if running
    echo "Stopping DirectoryWatcher..."
    if [[ -f "${AM_HOME}/${NAME_PREFIX}directory-watcher.pid" ]]; then
        PID=$(cat "${AM_HOME}/${NAME_PREFIX}directory-watcher.pid")
        if pgrep -F "${AM_HOME}/${NAME_PREFIX}directory-watcher.pid" > /dev/null 2>&1; then
            echo "Killing DirectoryWatcher process (PID: $PID)"
            kill -TERM $PID > /dev/null 2>&1
            sleep 2
            if pgrep -F "${AM_HOME}/${NAME_PREFIX}directory-watcher.pid" > /dev/null 2>&1; then
                echo "Force killing DirectoryWatcher process (PID: $PID)"
                kill -KILL $PID > /dev/null 2>&1
            fi
        fi
        rm -f "${AM_HOME}/${NAME_PREFIX}directory-watcher.pid"
        echo "DirectoryWatcher stopped"
    else
        echo "DirectoryWatcher PID file not found"
    fi
fi
# Remove persisted installation name if it matches the targeted one or if none specified
if [[ -z "$INSTALLATION_NAME" || "$INSTALLATION_NAME" == "$(cat "$INSTALLATION_NAME_FILE" 2>/dev/null | tr -d '[:space:]')" ]]; then
    rm -f "$INSTALLATION_NAME_FILE" > /dev/null 2>&1
fi
exit 0
