#!/bin/bash

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

readonly AEMBIT_GROUP_NAME="aembit"
readonly AEMBIT_AGENT_PROXY_USER_NAME="aembit_agent_proxy"
readonly AEMBIT_AGENT_PROXY_SYSTEMD_UNIT="aembit_agent_proxy.service"
readonly AEMBIT_AGENT_PROXY_INSTALL_DIR="/opt/aembit/edge/agent_proxy"
readonly AEMBIT_AGENT_PROXY_JOURNALD_CONFIG_FILE="/etc/systemd/journald@aembit_agent_proxy.conf"
LOG_FILE=$(dirname "${0}")/installer.log
readonly LOG_FILE
readonly AEMBIT_AGENT_PROXY_VERSION="1.14.2011"

readonly SYSTEMD_UNIT_FILES_FOLDER="/etc/systemd/system"
readonly SUDOERSD_DIR="/etc/sudoers.d"
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 memebers.
    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_AGENT_PROXY_USER_NAME}"
    if run_command getent passwd "${AEMBIT_AGENT_PROXY_USER_NAME}"; then
        run_command userdel -r "${AEMBIT_AGENT_PROXY_USER_NAME}"
    else
        log_warn "User '${AEMBIT_AGENT_PROXY_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 agent proxy"
    if [ -e "${AEMBIT_AGENT_PROXY_JOURNALD_CONFIG_FILE}" ]; then
        rm -f "${AEMBIT_AGENT_PROXY_JOURNALD_CONFIG_FILE}"
        run_command systemctl restart systemd-journald
    else
        log_warn "Aembit agent journald config ${AEMBIT_AGENT_PROXY_JOURNALD_CONFIG_FILE} doesn't exit"
    fi
}

finish_cleanup() {
    if [ -e "${AEMBIT_AGENT_PROXY_INSTALL_DIR}"/"${AEMBIT_AGENT_PROXY_VERSION}" ]; then
        run_command rm -rf "${AEMBIT_AGENT_PROXY_INSTALL_DIR}"/"${AEMBIT_AGENT_PROXY_VERSION}"
    else
        log_warn "Aembit agent proxy version ${AEMBIT_AGENT_PROXY_INSTALL_DIR}/${AEMBIT_AGENT_PROXY_VERSION} doesn't exit"
    fi
}

remove_ap_systemd_service() {
    log_info "Stopping and removing Aembit agent proxy service"
    run_command systemctl stop "${AEMBIT_AGENT_PROXY_SYSTEMD_UNIT}"
    run_command systemctl disable "${AEMBIT_AGENT_PROXY_SYSTEMD_UNIT}"

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

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

    run_command systemctl daemon-reload
    run_command systemctl reset-failed
}

remove_sudoers_file() {
    rm "${SUDOERSD_DIR}/aembit_agent_proxy"
}

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

init_log
remove_ap_systemd_service
remove_sudoers_file
# journald log configuration for aembit_agent_proxy 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
