#!/bin/bash

export PATH="${PATH}:/bin:/sbin:/usr/bin:/usr/sbin"

readonly AEMBIT_GROUP_NAME="aembit"
readonly AEMBIT_MCP_GATEWAY_USER_NAME="aembit_mcp_gateway"
readonly AEMBIT_MCP_GATEWAY_SYSTEMD_UNIT="aembit_mcp_gateway.service"
readonly AEMBIT_MCP_GATEWAY_INSTALL_DIR="/opt/aembit/edge/mcp_gateway"
readonly AEMBIT_MCP_GATEWAY_JOURNALD_CONFIG_FILE="/etc/systemd/journald@aembit_mcp_gateway.conf"
SCRIPT_DIR=$(dirname "${0}")
LOG_FILE="${SCRIPT_DIR}/installer.log"
readonly LOG_FILE
readonly LIB_DIR="${SCRIPT_DIR}/lib"
readonly AEMBIT_MCP_GATEWAY_VERSION="1.30.4549"

# Source common functions
# shellcheck source=lib/common_functions.sh
# shellcheck disable=SC1091
source "${LIB_DIR}/common_functions.sh"

readonly SYSTEMD_UNIT_FILES_FOLDER="/etc/systemd/system"
readonly MIN_SYSTEMD_VERSION_WITH_NAMESPACE_JOURNALS=245

log() {
    local level="${1}"
    shift

    local log_fmt="%s %s\n"
    if [ "${level}" ]; then
        log_fmt="%s ${level} %s\n"
    fi

    for line in "$@"; do
        # shellcheck disable=SC2059
        printf "${log_fmt}" "$(date +"%H:%M:%S")" "${line}" | tee -a "${LOG_FILE}"
    done
}

log_info() {
    log "Info:" "$@"
}

log_warn() {
    log "Warning:" "$@"
}

log_err() {
    log "Error:" "$@"
}

run_command() {
    local output=
        output="$("${@}" 2>&1)"
    local exit_code=$?
    if [ "${exit_code}" -ne 0 ]; then
        log_err "command '${*}' failed with error code: ${exit_code}, output: ${output}"
    fi
    return ${exit_code}
}

# get systemd version using systemctl
get_systemd_version() {
    systemd_version_output=$(systemctl --version)
    echo "$systemd_version_output" | grep -oP 'systemd \K\d+' | tr -dc '0-9'
}

# is_group_empty function is now sourced from lib/common_functions.sh

remove_aembit_user_and_group() {
    log_info "Removing Aembit user ${AEMBIT_MCP_GATEWAY_USER_NAME}"
    if getent passwd "${AEMBIT_MCP_GATEWAY_USER_NAME}" >/dev/null 2>&1; then
        run_command userdel -r "${AEMBIT_MCP_GATEWAY_USER_NAME}"
    else
        log_warn "User '${AEMBIT_MCP_GATEWAY_USER_NAME}' doesn't exist"
    fi

    if is_group_empty ${AEMBIT_GROUP_NAME}; then
        log_info "Removing Aembit group ${AEMBIT_GROUP_NAME}"
        run_command groupdel "${AEMBIT_GROUP_NAME}"
    fi
}

init_log() {
    touch "${LOG_FILE}"
}

remove_log_conf() {
    log_info "Removing journald configuration for Aembit MCP Gateway"
    if [ -e "${AEMBIT_MCP_GATEWAY_JOURNALD_CONFIG_FILE}" ]; then
        rm -f "${AEMBIT_MCP_GATEWAY_JOURNALD_CONFIG_FILE}"
        run_command systemctl restart systemd-journald
    else
        log_warn "Aembit MCP Gateway journald config ${AEMBIT_MCP_GATEWAY_JOURNALD_CONFIG_FILE} doesn't exist"
    fi
}

finish_cleanup() {
    if [ -e "${AEMBIT_MCP_GATEWAY_INSTALL_DIR}"/"${AEMBIT_MCP_GATEWAY_VERSION}" ]; then
        run_command rm -rf "${AEMBIT_MCP_GATEWAY_INSTALL_DIR}"/"${AEMBIT_MCP_GATEWAY_VERSION}"
    else
        log_warn "Aembit MCP Gateway version ${AEMBIT_MCP_GATEWAY_INSTALL_DIR}/${AEMBIT_MCP_GATEWAY_VERSION} doesn't exist"
    fi
}

remove_mcpgateway_systemd_service() {
    log_info "Stopping and removing Aembit MCP Gateway service"

    if systemctl is-active --quiet "${AEMBIT_MCP_GATEWAY_SYSTEMD_UNIT}" 2>/dev/null; then
        run_command systemctl stop "${AEMBIT_MCP_GATEWAY_SYSTEMD_UNIT}"
    fi
    if systemctl is-enabled --quiet "${AEMBIT_MCP_GATEWAY_SYSTEMD_UNIT}" 2>/dev/null; then
        run_command systemctl disable "${AEMBIT_MCP_GATEWAY_SYSTEMD_UNIT}"
    fi

    if [ -e "${SYSTEMD_UNIT_FILES_FOLDER}/${AEMBIT_MCP_GATEWAY_SYSTEMD_UNIT}" ]; then
        rm -f "${SYSTEMD_UNIT_FILES_FOLDER}/${AEMBIT_MCP_GATEWAY_SYSTEMD_UNIT}"
    fi

    run_command systemctl daemon-reload
    
    # Only reset failed state if the unit exists in systemd
    if systemctl list-units --all --full --no-legend "${AEMBIT_MCP_GATEWAY_SYSTEMD_UNIT}" 2>/dev/null | grep -q "${AEMBIT_MCP_GATEWAY_SYSTEMD_UNIT}"; then
        run_command systemctl reset-failed "${AEMBIT_MCP_GATEWAY_SYSTEMD_UNIT}"
    fi
}

log_info "Uninstalling Aembit MCP Gateway"
if [ "$(id --user)" -ne 0 ]; then
    log_err "Uninstaller must be run as root."
    exit 1
fi

init_log
remove_mcpgateway_systemd_service
# journald log configuration for aembit_mcp_gateway namespace is only added for versions >= 245.
if [ "$(get_systemd_version)" -ge "${MIN_SYSTEMD_VERSION_WITH_NAMESPACE_JOURNALS}" ]; then
    remove_log_conf
fi
remove_aembit_user_and_group
finish_cleanup

exit 0
