#!/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"
LOG_FILE=$(dirname "${0}")/installer.log
readonly LOG_FILE
readonly AEMBIT_MCP_GATEWAY_VERSION="1.26.3841"

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

# Check if the aembit user group can be deleted.
is_group_empty() {
    local group_name=$1
    # Check if the group exists and it has members.
    if run_command getent group "${group_name}"; then
        # Get the group id for the group
        gid=$(grep ^"${group_name}": < /etc/group | cut -d":" -f3)
        # List of users in /etc/passwd with gid set
        members=$(cut -d":" -f4 < /etc/passwd | grep -x "$gid")
        # If there are no users using gid, the group is empty.
        [ -z "$members" ] && return 0
    fi
    return 1
}

remove_aembit_user_and_group() {
    log_info "Removing Aembit user ${AEMBIT_MCP_GATEWAY_USER_NAME}"
    if run_command getent passwd "${AEMBIT_MCP_GATEWAY_USER_NAME}"; 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"
    run_command systemctl stop "${AEMBIT_MCP_GATEWAY_SYSTEMD_UNIT}"
    run_command systemctl disable "${AEMBIT_MCP_GATEWAY_SYSTEMD_UNIT}"

    if [ ! -e "${SYSTEMD_UNIT_FILES_FOLDER}/${AEMBIT_MCP_GATEWAY_SYSTEMD_UNIT}" ]; then
        log_warn "${AEMBIT_MCP_GATEWAY_SYSTEMD_UNIT} file doesn't not exist, can't remove from systemd autostart"
        return
    fi

    rm -f "${SYSTEMD_UNIT_FILES_FOLDER}/${AEMBIT_MCP_GATEWAY_SYSTEMD_UNIT}"

    run_command systemctl daemon-reload
    run_command systemctl reset-failed
}

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
