#!/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.30.4523"

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
    local gid members group_entry supplementary_members
    
    # Check if the group exists
    if ! group_entry=$(getent group "${group_name}" 2>/dev/null); then
        return 1
    fi
    
    # Parse group entry to check for supplementary members (4th field)
    # Format: groupname:password:gid:member1,member2,...
    supplementary_members=$(echo "${group_entry}" | cut -d":" -f4)
    if [ -n "${supplementary_members}" ]; then
        # Group has supplementary members, not empty
        return 1
    fi
    
    # Get the group id for the group
    gid=$(echo "${group_entry}" | cut -d":" -f3)
    
    # Check for users with this group as their primary GID
    members=$(cut -d":" -f4 /etc/passwd 2>/dev/null | grep -x "$gid")
    
    # If there are no users using gid as primary and no supplementary members, the group is empty
    [ -z "$members" ] && return 0
    
    return 1
}

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}"
        run_command systemctl daemon-reload
        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
