#!/usr/bin/env bash
# vim: set encoding=utf-8 :
# vim: set fileencoding=utf-8 :

PS4='$LINENO: '
set -euo pipefail # Strict mode (e: exit on error, u: error on unset variables, o: pipefail)

# This script automates the installation and setup of the United Manufacturing Hub (UMH) and the Management Companion.
# It ensures necessary tools are in place, installs or updates the UMH, and sets up the Management Companion with appropriate configurations.

# TESTED:
# RHEL
# - INSTALL / UNINSTALL HELM / KUBECTL
# FLATCAR
# - INSTALL / UNINSTALL HELM / KUBECTL (but kubectl, helm are always re-created)

# Developer notes
# Use shfmt -i 4 -l -w ./installer/automatic/install.sh to format this script
# https://github.com/mvdan/sh
# go install mvdan.cc/sh/v3/cmd/shfmt@latest
#
# Use shellcheck ./installer/automatic/install.sh to lint this script
# https://github.com/koalaman/shellcheck
# sudo apt install shellcheck -y

##########################################################################################
#                         Environment Variable Configuration                            #
# This script, designed for setting up the United Manufacturing Hub (UMH) and           #
# Management Companion, starts by configuring various environment variables. These      #
# variables control aspects like tooling installation, Kubernetes configuration,        #
# and specific settings for UMH and the Management Companion. Default values are set,   #
# but can be overridden by external inputs. The script ensures all necessary tools      #
# and configurations are in place for a successful installation and setup.               #
##########################################################################################

# --- General Script Control Variables ---
# These variables control general aspects of the script's execution.

# ---- Host OS variables ----
# These variables will be later used to patch the config map `mgmtcompanion-config` for mgmtcompanion
arch="$(uname -m)"
export OS_ARCH=${arch:-}
export EXTERNAL_IP=${EXTERNAL_IP:-}
export EXTERNAL_IP_INTERFACE=${EXTERNAL_IP_INTERFACE:-}
export EXTERNAL_IP_GATEWAY=${EXTERNAL_IP_GATEWAY:-}
export DNS_SERVER=${DNS_SERVER:-}

export auto_select_external_ip=${AUTO_SELECT_EXTERNAL_IP:-false}
export auto_select_k3s_installation_dir=${AUTO_SELECT_K3S_INSTALLATION_DIR:-false}

# IGNORE_ERRORS: If set to true, the script will ignore errors and continue. Mainly used for troubleshooting.
export ignore_errors=${GENERAL_IGNORE_ERRORS:-false}
# TIMEOUT: Time in seconds to wait for a process before timeout. Default is 2 minutes.
export TIMEOUT=${GENERAL_TIMEOUT:-120}
# INTERVAL: Interval in seconds to check a process status. Default is every 5 seconds.
export INTERVAL=${GENERAL_INTERVAL:-5}
# RETRIES: Number of retries for a process. Default is 5.
export RETRIES=${GENERAL_RETRIES:-10}
export UNINSTALL=${UNINSTALL:-false}

# --- Tooling Installation Variables ---
# These variables are related to the installation of necessary tooling such as k3s, kubectl, and helm.

# INSTALL_K3S_VERSION: Specifies the version of k3s to be installed.
export INSTALL_K3S_VERSION=${TOOL_K3S_VERSION:-v1.29.5+k3s1}
export INSTALL_K3S_SELINUX_VERSION=${TOOL_K3S_SELINUX_VERSION:-k3s-selinux-1.5-1.el9.noarch.rpm}
# K3S_DATA_DIR: Specifies the data directory for k3s (No default value)
export K3S_DATA_DIR=${K3S_DATA_DIR:-}
# INSTALL_KUBECTL_VERSION: Specifies the version of kubectl to be installed.
export INSTALL_KUBECTL_VERSION=${TOOL_KUBECTL_VERSION:-v1.29.5}
# INSTALL_HELM_VERSION: Specifies the version of helm to be installed.
export INSTALL_HELM_VERSION=${TOOL_HELM_VERSION:-v3.13.2}
# CUSTOM_TLS_SAN: Specifies custom TLS Subject Alternative Names for the k3s installation.
export CUSTOM_TLS_SAN=${TOOL_K3S_CUSTOM_TLS_SAN:-}
# CUSTOM_DNS_SERVERS: Specifies custom DNS servers for the k3s CoreDNS configuration. (Comma separated list of DNS servers)
export CUSTOM_DNS_SERVERS=${TOOL_K3S_COREDNS_CUSTOM_DNS_SERVERS:-}

# --- Kubernetes Configuration Variables ---
# These variables define configurations for Kubernetes.

# KUBECONFIG: Path to the kubeconfig file to be used.
export KUBECONFIG=${TOOL_K3S_KUBECONFIG:-/etc/rancher/k3s/k3s.yaml}

# NODE_NAME: Name of the node in the Kubernetes cluster. Defaults to the hostname.
export NODE_NAME=${KUBE_NODE_NAME:-$(hostname)}
export auto_patch_hostname=${AUTO_PATCH_HOSTNAME:-false}

# --- Speedtest Configuration Variables ---
export MIN_DOWNLOAD=${SPEEDTEST_MIN_DOWNLOAD:-50000000} # Minimum download speed in bits per second (e.g., 50 Mbps)
export MIN_UPLOAD=${SPEEDTEST_MIN_UPLOAD:-10000000}     # Minimum upload speed in bits per second (e.g., 10 Mbps)
export MIN_PING=${SPEEDTEST_MIN_PING:-50}               # Maximum ping in milliseconds

export MEASURED_UPLOAD=0
export MEASURED_DOWNLOAD=0
export MEASURED_PING=0

# --- UMH Installation Variables ---
# Variables for installing, updating, or ensuring the existence of UMH.

# SKIP_UMH_INSTALL: If set to true, the script skips the UMH installation process.
export skip_umh_install=${UMH_SKIP_INSTALL:-false}
# FORCE_UMH_OVERWRITE: Forces an overwrite of an existing UMH installation if set to true.
export force_umh_overwrite=${UMH_FORCE_OVERWRITE:-false}
# UMH_VERSION: Specifies the version of UMH to be installed.
export UMH_VERSION=${UMH_VERSION:-0.27.0}
# UMH_HELM_CHART_URL: Specifies the URL for the UMH Helm chart.
export UMH_HELM_CHART_URL=${UMH_HELM_CHART_URL:-"https://management.umh.app/helm/umh"}
# ALLOW_HELM_PRERELEASE
export ALLOW_HELM_PRERELEASE=${ALLOW_HELM_PRERELEASE:-false}

# --- Management Companion Installation Variables ---
# These variables pertain to the installation and configuration of the Management Companion.

# AUTH_TOKEN: The authentication token required for the Management Companion.
export AUTH_TOKEN=${MGMT_AUTH_TOKEN:-}
# INSECURE_TLS_SKIP_CERTIFICATE_CHECK: Skips TLS certificate checks if set to true. Useful for development environments.
export insecure_tls_skip_certificate_check=${MGMT_INSECURE_TLS_SKIP_CERTIFICATE_CHECK:-false}
# CUSTOM_MGMT_URL: Sets a custom management URL for the Companion, for example, a specific Cloudflare branch.
export CUSTOM_MGMT_URL=${MGMT_CUSTOM_URL:-https://management.umh.app}
# Remove trailing slash (if any)
CUSTOM_MGMT_URL=${CUSTOM_MGMT_URL%/}
# IMAGE_VERSION: Specifies a custom image version for the Management Companion, such as 'staging'.
export IMAGE_VERSION=${MGMT_CUSTOM_IMAGE_VERSION:-latest}
# SKIP_COMPANION_INSTALL: If true, skips the installation of the Management Companion.
export skip_companion_install=${MGMT_SKIP_INSTALL:-false}
# SKIP_RHEL_SHA1_SIGNATURES skips checking on RHEL the SHA1 signatures
export SKIP_RHEL_SHA1_SIGNATURES=${MGMT_SKIP_RHEL_SHA1_SIGNATURES:-false}
# MGMT_CONFIG_DEBUG_DISABLE_BACKEND_CONNECTION: Disables the backend connection for debugging purposes.
export MGMT_CONFIG_DEBUG_DISABLE_BACKEND_CONNECTION=${MGMT_CONFIG_DEBUG_DISABLE_BACKEND_CONNECTION:-false}
# API_URL: URL for the UMH API endpoint.
export API_URL=${MGMT_API_URL:-$CUSTOM_MGMT_URL/api}
# STATIC_URL: URL for static resources of UMH.
export STATIC_URL=${MGMT_STATIC_URL:-$CUSTOM_MGMT_URL/static}
# Configuration and Kubernetes resource URLs
export CONFIGMAP_URL=${MGMT_CONFIGMAP_URL:-$STATIC_URL/kubernetes/configmap.yaml}
export SECRET_URL=${MGMT_SECRET_URL:-$STATIC_URL/kubernetes/secret.yaml}
export STATEFULSET_URL=${MGMT_STATEFULSET_URL:-$STATIC_URL/kubernetes/statefulset.yaml}
export ROLE_URL=${MGMT_ROLE_URL:-$STATIC_URL/kubernetes/role.yaml}
export ROLE_BINDING_URL=${MGMT_ROLE_BINDING_URL:-$STATIC_URL/kubernetes/rolebinding.yaml}
export PVC_URL=${MGMT_PVC_URL:-$STATIC_URL/kubernetes/pvc.yaml}
export KUBELET_URL=${MGMT_KUBELET_URL:-$STATIC_URL/kubernetes/kubelet-config.yaml}
export REGISTRIES_URL=${MGMT_REGISTRIES_URL:-$STATIC_URL/kubernetes/registries.yaml}

# LOCATION VARIABLES (Enterprise, Site, Area, Line, workCell)
export LOCATION_ENTERPRISE=${LOCATION_ENTERPRISE:-}
export LOCATION_SITE=${LOCATION_SITE:-}
export LOCATION_AREA=${LOCATION_AREA:-}
export LOCATION_LINE=${LOCATION_LINE:-}
export LOCATION_WORKCELL=${LOCATION_WORKCELL:-}
# UMH LITE
export IS_LITE_INSTALL=${IS_LITE_INSTALL:-false}

export IS_FULL_INSTALL=${IS_FULL_INSTALL:-true}
# if IS_LITE_INSTALL is true, set SKIP_UMH_INSTALL to true
if [[ $IS_LITE_INSTALL == true ]]; then
    export skip_umh_install=true
    export IS_FULL_INSTALL=false
fi

# Silent install (defaults to false)
export SILENT=${SILENT:-false}

# Skip Hardware test
export SKIP_HARDWARE_TEST=${SKIP_HARDWARE_TEST:-false}
export IGNORE_DISK_SPACE_ERROR=${IGNORE_DISK_SPACE_ERROR:-false}

# Disable Hardware test in statusmessage
# Enabling this will always return a good status, even if the disk space, memory, or CPU cores are not sufficient
export DISABLE_HARDWARE_STATUS_CHECK=${DISABLE_HARDWARE_STATUS_CHECK:-false}

# Release channel
# Channels:
# - enterprise (requires enterprise account)
# - stable (default)
# - nightly (unstable builds for testing)
export RELEASE_CHANNEL=${RELEASE_CHANNEL:-stable}

# Helm flags
export CHART_VERSION=$UMH_VERSION
export SAME_TOPIC_EXPERIENCE=${SAME_TOPIC_EXPERIENCE:-false}

# Environment Variables for Testing and Troubleshooting
# -----------------------------------------------------
# The following environment variables are intended for testing individual components
# of the install script. They are particularly useful during troubleshooting and debugging.
# Setting these variables allows the execution of specific sub-functions independently.
# By default, all these variables are set to 'false', indicating that no specific action
# is taken unless explicitly requested.
#
# INSTALL_HELM: Set to 'true' to only execute the Helm installation part of the script.
# UNINSTALL_HELM: Set to 'true' to only execute the Helm uninstallation part.
# INSTALL_KUBECTL: Set to 'true' to only execute the kubectl installation part.
# UNINSTALL_KUBECTL: Set to 'true' to only execute the kubectl uninstallation part.

INSTALL_HELM=${INSTALL_HELM:-false}
UNINSTALL_HELM=${UNINSTALL_HELM:-false}
INSTALL_KUBECTL=${INSTALL_KUBECTL:-false}
UNINSTALL_KUBECTL=${UNINSTALL_KUBECTL:-false}
INSTALL_KUBERNETES=${INSTALL_KUBERNETES:-false}
UNINSTALL_KUBERNETES=${UNINSTALL_KUBERNETES:-false}

# Configure temporary directory location
# This can be used to specify a different temporary directory for the installation
# For example when /tmp is not executable
export TMP_FILE_BASE_DIR=${TMP_FILE_BASE_DIR:-/tmp}

# Ensure TMP_FILE_BASE_DIR exists
mkdir -p "${TMP_FILE_BASE_DIR}"

# Set up TEMP_DIR using TMP_FILE_BASE_DIR
export TEMP_DIR="${TMP_FILE_BASE_DIR}/mgmt-installer"

# Ensure TEMP_DIR exists
mkdir -p "${TEMP_DIR}"

export SENTRY_DSN="https://abc@staging.management.umh.app/sentry/?project=installer"

## SENTRY

download_sentry() {
    curl -sSL "${CUSTOM_MGMT_URL}/binaries/sentry/linux/x86_64/sentry-cli" -o "${TEMP_DIR}/sentry-cli"
    chmod +x "${TEMP_DIR}/sentry-cli"

    eval "$("${TEMP_DIR}/sentry-cli" bash-hook)"
}
download_sentry

##########################################################################################
#                                 HELPER FUNCTIONS                                       #
# This section contains helper functions and initializations used throughout the script. #
##########################################################################################

# Function to source environment files and update PATH
source_environment_and_update_path() {
    if [[ "$OS" == "rhel" ]]; then
        # Source ~/.bashrc & ~/.bash_profile

        # Note: This shellcheck directive is used to suppress the warning SC1090
        # shellcheck source=/dev/null
        source ~/.bash_profile || true
        # shellcheck source=/dev/null
        source ~/.bashrc || true

        # Also add /usr/local/bin/ to path if not already
        if [[ ":$PATH:" != *":/usr/local/bin:"* ]]; then
            # Add /usr/local/bin to PATH
            PATH="/usr/local/bin:$PATH"
        fi
    fi
}

# Function to create a temporary directory
recreate_temporary_directory() {
    rm -rf "$TEMP_DIR" || true # First remove any existing directory, to start with a clean state
    if ! mkdir -p "$TEMP_DIR"; then
        handleError "Failed to create temporary directory at $TEMP_DIR" "Check file permissions."
        exit 1
    fi
}

## Loggers
function logMessage {
    local emoji=$1
    local message=$2
    if ! mkdir -p "$TEMP_DIR"; then
        handleWarning "Failed to create temporary directory at $TEMP_DIR"
    fi
    # If mgmt_install.log does not exist, touch it
    if [ ! -f $TEMP_DIR/mgmt_install.log ]; then
        if ! touch $TEMP_DIR/mgmt_install.log; then
            handleWarning "Failed to create log file at $TEMP_DIR/mgmt_install.log"
        fi
    fi

    echo -e "$emoji $message"
    echo "$emoji $message" >>$TEMP_DIR/mgmt_install.log || true
}

function logToSentry {

    sentryTags=""

    # Collect system information.
    ## System Vendor
    sysVendor=$(cat /sys/class/dmi/id/sys_vendor 2>/dev/null || echo 'unknown')
    # Replace spaces with underscores
    sysVendor=$(echo $sysVendor | tr ' ' '_')
    sysVendor="sysVendor:$sysVendor"
    sentryTags="$sentryTags -t $sysVendor"

    ## CPU Vendor
    cpuVendor=$(lscpu | grep "Vendor ID" | awk -F ':' '{print $2}' | xargs 2>/dev/null || echo 'unknown')
    # Replace spaces with underscores
    cpuVendor=$(echo $cpuVendor | tr ' ' '_')
    cpuVendor="cpuVendor:$cpuVendor"
    sentryTags="$sentryTags -t $cpuVendor"

    ## CPU Model
    cpuModel=$(lscpu | grep "Model name" | awk -F ':' '{print $2}' | xargs 2>/dev/null || echo 'unknown')
    # Replace spaces with underscores
    cpuModel=$(echo $cpuModel | tr ' ' '_')
    cpuModel="cpuModel:$cpuModel"
    sentryTags="$sentryTags -t $cpuModel"

    ## CPU Cores
    cpuCores=$(lscpu | grep "^CPU(s):" | awk -F ':' '{print $2}' | xargs 2>/dev/null || echo 'unknown')
    cpuCores="cpuCores:$cpuCores"
    sentryTags="$sentryTags -t $cpuCores"

    ## Memory
    memory=$(free -m | awk '/^Mem:/{print $2}' 2>/dev/null || echo 'unknown')
    memory="memory:$memory"
    sentryTags="$sentryTags -t $memory"

    ## Disk Size
    # Extract the name, size, and usage of the disk mounted at /
    disk_info=$(lsblk -o NAME,SIZE,MOUNTPOINTS -nr | awk '$3 == "/" {print $1, $2}')

    # Generate the -e options list
    if [ -n "$disk_info" ]; then
        read -r disk_name disk_size <<<"$disk_info"
        disk_usage=$(df -h --output=used -x tmpfs -x devtmpfs / | tail -n 1)

        # Strip whitespaces
        disk_name=$(echo $disk_name | tr -d ' ')
        disk_size=$(echo $disk_size | tr -d ' ')
        disk_usage=$(echo $disk_usage | tr -d ' ')

        sentryExtra="-e disk_name:$disk_name -e disk_size:$disk_size -e disk_usage:$disk_usage"
    else
        echo "No disk mounted at /"
        sentryExtra="-e disk_name:unknown -e disk_size:unknown -e disk_usage:unknown"
    fi

    # Network performance variables
    if [ -n "$MEASURED_UPLOAD" ]; then
        upload="upload:$MEASURED_UPLOAD"
        sentryTags="$sentryTags -t $upload"
    fi

    if [ -n "$MEASURED_DOWNLOAD" ]; then
        download="download:$MEASURED_DOWNLOAD"
        sentryTags="$sentryTags -t $download"
    fi

    if [ -n "$MEASURED_PING" ]; then
        ping="ping:$MEASURED_PING"
        sentryTags="$sentryTags -t $ping"
    fi

    "${TEMP_DIR}/sentry-cli" send-event -m "$1" --logfile $TEMP_DIR/mgmt_install.log $sentryTags $sentryExtra -l $2 || true
}

function handleError {
    logMessage "❌ Error:" "$1"
    logMessage "💡 Tip:" "$2"

    logToSentry "$1" "error"

    # Skip lower part if ignore_errors is set
    if [[ $ignore_errors == true ]]; then
        # Sleep so the user has time to read the error
        sleep 1
        return
    fi

    logMessage "ℹ️" " For more details, check the logs at $TEMP_DIR/mgmt_install.log"

    # Prompt user if they want to display the log file contents
    read -r -p "❓ Do you want to display the log file contents? (Y/n): " display_log
    display_log=${display_log:-Y}
    if [[ $display_log =~ ^[Yy]$ ]]; then
        cat $TEMP_DIR/mgmt_install.log
    fi

    exit 1
}

function handleInfo {
    logMessage "📢" "$1"
}

function handleSuccess {
    logMessage "  ✅" "$1"
}

function handleStep {
    logMessage "🔧" "$1"
}

function handleCheck {
    logMessage "🔍" "$1"
}

function handleWarning {
    logMessage "⚠️" "$1"
}

function handleSleep {
    logMessage "⏳" "$1"
    sleep "$2"
}

function handleSecurity {
    logMessage "🔓" "$1"
}

function handleInstalled {
    logMessage "🎉" "$1"
}

##########################################################################################
#                                Verify System                                           #
# This step includes initial checks and configurations for the installation process.     #
# It verifies execution as root, identifies the operating system, performs OS-specific   #
# checks, and validates critical elements like internet                                  #
# connectivity.                                                                          #
##########################################################################################

OS="generic"
OS_VERSION="generic"

set_OS_info() {
    handleCheck "Identifying the operating system..."

    # Check for WSL string in /proc/version
    if [[ -f /proc/version ]] && [[ -f /proc/sys/kernel/osrelease ]]; then
        if grep -qE "microsoft" /proc/sys/kernel/osrelease; then
            if grep -qE "WSL2" /proc/version; then
                handleWarning "WSL2 is not supported, we will try to continue, but this is not recommended."
            else
                handleWarning "WSL1 is not supported, we will try to continue, but this is not recommended."
            fi
        fi
    fi

    if [[ -f /etc/os-release ]]; then
        source /etc/os-release
        OS=$ID
        OS_VERSION=$VERSION_ID
        handleSuccess "Operating System detected: $OS, Version: $OS_VERSION"

        case $OS in
        "rhel" | "rocky")
            # Check if RHEL version is supported
            if [[ $OS_VERSION =~ ^9\.[0-9]+$ ]]; then
                handleSuccess "RHEL version $OS_VERSION is supported."
            else
                # Ask user for confirmation (or continue if SILENT is set)
                if [[ "$SILENT" == "true" ]]; then
                    handleWarning "SILENT is set. Skipping confirmation..."
                else
                    handleWarning "Unsupported RHEL version: $OS_VERSION" "RHEL 9.0 or higher is recommended."
                    read -r -p "❓ Do you want to continue? [Unsupported] (Y/n): " confirm
                    confirm=${confirm:-Y}
                    if [[ ! $confirm =~ ^[Yy]$ ]]; then
                        handleError "Aborting..." "You can run the script again to install MgmtCompanion."
                    fi
                fi
            fi
            ;;
        "flatcar")
            # Placeholder for checking supported Flatcar versions
            # Currently supporting all versions
            handleSuccess "Flatcar version $OS_VERSION is supported."
            ;;
        "ubuntu")
            # Support Ubuntu 22.04.4
            if [[ $OS_VERSION == "22.04" ]]; then
                handleSuccess "Ubuntu version $OS_VERSION is supported."
            else
                # Ask user for confirmation (or continue if SILENT is set)
                if [[ "$SILENT" == "true" ]]; then
                    handleWarning "SILENT is set. Skipping confirmation..."
                else
                    handleWarning "Unsupported Ubuntu version: $OS_VERSION" "Ubuntu 22.04 LTS is recommended."
                    read -r -p "❓ Do you want to continue? [Unsupported] (Y/n): " confirm
                    confirm=${confirm:-Y}
                    if [[ ! $confirm =~ ^[Yy]$ ]]; then
                        handleError "Aborting..." "You can run the script again to install MgmtCompanion."
                    fi
                fi
            fi
            ;;
        *)
            handleWarning "Unknown OS, but proceed on your own risk: $OS"
            ;;
        esac
    else
        handleError "Unable to identify the operating system." "Please ensure /etc/os-release is present."
    fi
}

check_root_user() {
    # --- Check Execution as Root User ---
    handleCheck "Checking for root user..."
    if [[ $EUID -ne 0 ]]; then
        handleError "This script must be run as root." "Use 'sudo ./install.sh' to execute it as root."
    else
        handleSuccess "Root user detected: $(whoami)"
    fi
}

check_min_requirements() {
    # Dont run if SKIP_HARDWARE_TEST is set
    if [[ $SKIP_HARDWARE_TEST == true ]]; then
        handleWarning "Skipping hardware test."
        return
    fi

    # CPU: Minimum 4 cores
    # Memory: 16GB RAM
    # Disk Space: 200GB available

    # These are not hard requirements, but recommended

    ## CPU
    handleCheck "Checking CPU cores..."
    local cpu_cores
    cpu_cores=$(grep -c ^processor /proc/cpuinfo)
    if [[ $cpu_cores -lt 4 ]]; then
        handleError "Insufficient CPU cores detected: $cpu_cores" "A minimum of 4 CPU cores is recommended."
    else
        handleSuccess "CPU cores detected: $cpu_cores"
    fi

    handleCheck "Checking memory..."
    local memory
    memory=$(free --giga | awk '/^Mem:/{print $2}')
    if [[ $IS_LITE_INSTALL == false ]]; then
      # 16GB is the recommended memory
      # Lowering the threshold to 14GB (90% of 16GB)
      adjusted_min_memory=14745
      memory_in_mb=$(( memory * 1024 ))
      if (( memory_in_mb < adjusted_min_memory )); then
          handleError "Insufficient memory detected: $memory Gigabytes" "A minimum of 16 GB RAM is recommended in production. Use SKIP_HARDWARE_TEST=true to skip this check for development systems."
        else
          handleSuccess "Memory detected: $memory Gigabytes"
        fi
    else
        handleSuccess "Memory detected: $memory Gigabytes"
    fi

    handleCheck "Checking disk space..."
    local disk_space
    # Currently the disk space checks only for available space in the root
    # partition as it is the default storage used by K3s for its workloads.
    disk_space=$(df -B1 / | awk '$NF=="/"{print $4}')
    # 200GB is the recommended disk space
    # 90% of 200GB = 180GB. Lowering the threshold to 180GB
    adjusted_min_disk_space=$(( 180 * 1000 * 1000 * 1000 ))
    if (( disk_space < adjusted_min_disk_space )); then
        handleError "Insufficient disk space detected: $disk_space bytes" "A minimum of 200GB free disk space is recommended in production. Use SKIP_HARDWARE_TEST=true to skip this check for development systems."
    else
        handleSuccess "Disk space detected: $disk_space bytes"
    fi

    # Check that CPU is x86_64 using uname -mpi
    handleCheck "Checking if CPU is x86_64"
    if ! uname -mpi | grep -q 'x86_64'; then
        handleError "Incompatible CPU detected" "k3s requires an x86_64 cpu."
    fi

    # Check if required CPU instructions are available
    handleCheck "Checking for required CPU instructions..."
    ## SSE 4.2 is a HARD requirement for redpanda.
    ### IS_LITE_INSTALL is set to true, so we can skip this check (LITE does not install redpanda)
    if [[ $IS_LITE_INSTALL == false ]]; then
        # https://github.com/ClickHouse/ClickHouse/issues/20#issuecomment-226849297
        if grep -q 'Common KVM processor' /proc/cpuinfo; then
            handleWarning "CPU instruction checking on KVM is buggy, skipping"
        else
            if ! grep -q sse4_2 /proc/cpuinfo; then
                # https://github.com/redpanda-data/redpanda/blob/594c3eda5f025c3cd5810cef0980b965bc5b447e/src/v/syschecks/include/syschecks/syschecks.h#L47
                handleError "CPU does not support SSE 4.2." "A CPU with SSE 4.2 support is required."
            else
                handleSuccess "CPU supports SSE 4.2."
            fi
        fi
    else
        handleSuccess "Skipping SSE 4.2 check for LITE installation."
    fi

    handleSuccess "Minimum requirements check completed successfully."
}

verify_system() {
    source_environment_and_update_path

    # --- OS-Specific Checks and Configurations ---

    # Function to check registration and version for RHEL
    check_rhel_registration_and_version() {
        handleCheck "Checking RHEL registration status..."
        if ! subscription-manager status >>$TEMP_DIR/mgmt_install.log 2>&1; then
            handleError "RHEL machine registration check failed." "Verify registration status with 'subscription-manager status'."
        else
            handleSuccess "RHEL machine is registered."
        fi
    }

    check_min_requirements

    # Execute checks based on detected OS
    case $OS in
    "rhel")
        check_rhel_registration_and_version
        ;;
    *)
        handleWarning "No additional checks for OS: $OS"
        ;;
    esac

    handleCheck "Checking for internet connection..."
    ## Check if $CUSTOM_MGMT_URL is resolvable (dns)
    handleCheck "Checking if $CUSTOM_MGMT_URL is resolvable..."
    # Remove https:// from url
    URL_WITHOUT_PROTOCOL=${CUSTOM_MGMT_URL#*://}

    # Remove tailing slash (if any)
    URL_WITHOUT_PROTOCOL=${URL_WITHOUT_PROTOCOL%/}

    # Retry ${RETRIES} times with ${INTERVAL} seconds interval
    resolved=false
    for ((i = 1; i <= RETRIES; i++)); do
        if ! $DIG_PATH +short "$URL_WITHOUT_PROTOCOL" >>$TEMP_DIR/mgmt_install.log 2>&1; then
            handleWarning "$URL_WITHOUT_PROTOCOL is not resolvable." "Retrying in ${INTERVAL} seconds..."
            sleep ${INTERVAL}
        else
            handleSuccess "$URL_WITHOUT_PROTOCOL can be resolved."
            resolved=true
            break
        fi
    done
    if [[ $resolved == false ]]; then
        handleError "$URL_WITHOUT_PROTOCOL is not resolvable." "Check your network connection or try again later."
    fi

    ## Check if $CUSTOM_MGMT_URL is reachable (http) (5 retries with ${INTERVAL} seconds interval) using curl
    handleCheck "Checking if $CUSTOM_MGMT_URL is reachable..."
    reachable=false
    for ((i = 1; i <= RETRIES; i++)); do
        # This is the only case where we directly invoke CURL, as we need to check the HTTP status code
        if ! $CURL_PATH -s -o /dev/null -w "%{http_code}" "$CUSTOM_MGMT_URL" >>$TEMP_DIR/mgmt_install.log 2>&1; then
            handleWarning "$CUSTOM_MGMT_URL is not reachable." "Retrying in ${INTERVAL} seconds..."
            sleep ${INTERVAL}
        else
            handleSuccess "$CUSTOM_MGMT_URL is reachable."
            reachable=true
            break
        fi
    done
    if [[ $reachable == false ]]; then
        handleError "$CUSTOM_MGMT_URL is not reachable." "Check your network connection or try again later."
    fi

    # http or https
    PROTOCOL_WITHOUT_URL=$(echo "${CUSTOM_MGMT_URL%%://*}" | tr '[:upper:]' '[:lower:]')
    if [[ $PROTOCOL_WITHOUT_URL == "http" ]]; then
        handleSuccess "URL is HTTP, skipping certificate check"
        return
    elif [[ $PROTOCOL_WITHOUT_URL == "https" ]]; then
        handleSuccess "URL is HTTPS, checking certificate"
    else
        handleError "Invalid protocol: $PROTOCOL_WITHOUT_URL" "Only HTTP and HTTPS are supported"
    fi

    function check_certificate {
        local expected_issuer="O=Let'sEncrypt"
        # Remove https:// from url
        URL_WITHOUT_PROTOCOL=${CUSTOM_MGMT_URL#*://}
        # Remove trailing slash (if any)
        URL_WITHOUT_PROTOCOL=${URL_WITHOUT_PROTOCOL%/}
        handleStep "Checking certificate for $URL_WITHOUT_PROTOCOL"

        # Declare the variable
        local cert_output
        # Assign the output of the command to the variable
        cert_output=$( (
            sleep 1
            echo "quit"
        ) | openssl s_client -connect "$URL_WITHOUT_PROTOCOL":443 -servername "$URL_WITHOUT_PROTOCOL" -showcerts)
        echo "$cert_output" | awk '/-----BEGIN CERTIFICATE-----/,/-----END CERTIFICATE-----/' >$TEMP_DIR/certificates.pem

        IS_LETSENCRYPT_ISSUED="true"
        # Check for the Let's Encrypt issuer in the certificate
        if ! openssl x509 -in $TEMP_DIR/certificates.pem -noout -text | grep -q "DNS:$URL_WITHOUT_PROTOCOL"; then
            handleWarning "Certificate does not contain Subject Alternate Name for $URL_WITHOUT_PROTOCOL", "Please contact your administrator"
            IS_LETSENCRYPT_ISSUED="false"
        fi
        if ! openssl x509 -in $TEMP_DIR/certificates.pem -noout -issuer | tr -d ' ' | grep -q "$expected_issuer"; then
            handleWarning "TLS certificate not issued by Let's Encrypt, assuming interception" "If you are unsure what this means, DO NOT continue the installation"
            IS_LETSENCRYPT_ISSUED="false"
        fi
    }

    ## Check if $CUSTOM_MGMT_URL is intercepted by a proxy
    handleCheck "Checking if $CUSTOM_MGMT_URL is intercepted by a proxy..."
    check_certificate
    if [[ $IS_LETSENCRYPT_ISSUED == "true" ]]; then
        handleSuccess "$CUSTOM_MGMT_URL is not intercepted by a proxy."
    else
        if [[ $insecure_tls_skip_certificate_check == true ]]; then
            handleWarning "$CUSTOM_MGMT_URL is intercepted by a proxy." "Ignoring check because INSECURE_TLS_SKIP_CERTIFICATE_CHECK is set."
        else
            handleWarning "$CUSTOM_MGMT_URL is intercepted by a proxy." "Ensure your DNS is configured correctly or set INSECURE_TLS_SKIP_CERTIFICATE_CHECK to true to ignore this check."
            # Ask user for confirmation (or continue if SILENT is set)
            if [[ "$SILENT" == "true" ]]; then
                handleWarning "SILENT is set. Skipping confirmation..."
            else
                read -r -p "❓ Do you want to continue? [INSECURE] (Y/n): " confirm
                confirm=${confirm:-Y}
                if [[ ! $confirm =~ ^[Yy]$ ]]; then
                    handleError "Aborting..." "You can run the script again to install MgmtCompanion."
                fi
                # Set INSECURE_TLS_SKIP_CERTIFICATE_CHECK to true
                export insecure_tls_skip_certificate_check=true
            fi
        fi
    fi

    handleSuccess "Initial verification succeeded. Now proceeding to the tool installation..."
}

# Function to handle the output
handle_result() {

    if [[ $MEASURED_DOWNLOAD -lt $MIN_DOWNLOAD ]]; then
        handleWarning "Download speed is too low: $MEASURED_DOWNLOAD"
        handleWarning "Setting interval to 10 seconds, retries to 40, timeout to 240 seconds to avoid network connectivity issues"
        INTERVAL=10
        RETRIES=40
        TIMEOUT=240
    else
        handleCheck "Download speed is sufficient: $MEASURED_DOWNLOAD"
    fi

    if [[ $MEASURED_UPLOAD -lt $MIN_UPLOAD ]]; then
        handleWarning "Upload speed is too low: $MEASURED_UPLOAD"
        handleWarning "Setting interval to 10 seconds, retries to 40, timeout to 240 seconds to avoid network connectivity issues"
        INTERVAL=10
        RETRIES=40
        TIMEOUT=240
    else
        handleCheck "Upload speed is sufficient: $MEASURED_UPLOAD"
    fi

    if [[ $MEASURED_PING -gt $MIN_PING ]]; then
        handleWarning "Ping is too high: $MEASURED_PING"
        handleWarning "Setting interval to 10 seconds, retries to 40, timeout to 240 seconds to avoid network connectivity issues"
        INTERVAL=10
        RETRIES=40
        TIMEOUT=240
    else
        handleCheck "Ping is within acceptable limits: $MEASURED_PING"
    fi
}

# Function to perform speed test and check results
perform_speed_test() {
    local speedtest_output
    local python_cmd

    # Check for Python 3 or Python and create appropriate command
    if command -v python3 &>/dev/null; then
        python_cmd="python3"
    elif command -v python &>/dev/null; then
        python_cmd="python"
    else
        handleWarning "Python is not installed. Skipping speed test."
        return 1
    fi

    if ! downloadFile "${CUSTOM_MGMT_URL}/binaries/speedtest-cli" "$TEMP_DIR/speedtest-cli"; then
        handleError "Failed to download speedtest-cli.py" "Check your network connection and try again."
    fi
    if ! chmod +x "$TEMP_DIR/speedtest-cli" >>$TEMP_DIR/mgmt_install.log 2>&1; then
        handleError "Failed to make speedtest-cli executable." "Check the file permissions and try again."
    fi

    # Execute the speed test
    handleStep "Performing speed test..."
    speedtest_output=$($python_cmd "$TEMP_DIR/speedtest-cli" --json)
    if [ $? -ne 0 ]; then
        handleWarning "Failed to perform speed test."
        return 1
    fi

    # Parse the JSON output and update global variables
    MEASURED_UPLOAD=$(echo "$speedtest_output" | jq '.upload | floor')
    MEASURED_DOWNLOAD=$(echo "$speedtest_output" | jq '.download | floor')
    MEASURED_PING=$(echo "$speedtest_output" | jq '.ping | floor')

    # Output results and check them
    handle_result

    return 0
}

adjust_interval_based_on_speedtest() {
    if ! perform_speed_test; then
        handleWarning "Setting interval to 10 seconds, retries to 40, timeout to 240 seconds to avoid network connectivity issues"
        INTERVAL=10
        RETRIES=40
        TIMEOUT=240
    fi
}

# Function to validate numeric input
validate_numeric_input() {
    local prompt="$1"
    local min="$2"
    local max="$3"
    local default="$4"
    local silent="$5"

    while true; do
        # If in silent mode and default is provided, use it
        if [[ "$silent" == "true" && -n "$default" ]]; then
            echo "$default"
            return 0
        fi

        # Flush stdout and stderr
        echo -n >/dev/stdout
        echo -n >/dev/stderr

        # Read input
        read -r -p "❓ $prompt" choice

        # If empty and default provided, use default
        if [[ -z "$choice" && -n "$default" ]]; then
            echo "$default"
            return 0
        fi

        # Check if input contains only digits and is within range
        if ! [[ "$choice" =~ ^[0-9]+$ ]]; then
            continue
        fi

        # Convert to number and check range
        if ((choice >= min && choice <= max)); then
            echo "$choice"
            return 0
        else
            continue
        fi
    done
}

ask_external_ip() {
    interface_list=()
    # Fetch IPV4 addresses of all network interfaces except docker, loopback, veth, tun, tap,tailscale and bridge interfaces
    for i in $(ip -o -4 addr show | awk '{print $2}' | uniq); do
        if [[ "$i" != docker* ]] && [[ "$i" != lo* ]] && [[ "$i" != veth* ]] && [[ "$i" != flannel* ]] &&
            [[ "$i" != tun* ]] && [[ "$i" != tap* ]] && [[ "$i" != "br-*" ]] && [[ "$i" != cni* ]] && [[ "$i" != tailscale* ]]; then
            ip_addr=$(ip -o -4 addr show "$i" | awk '{print $4}' | head -n1)
            # Trim the Cidr notation suffix /24 from the IP address
            interface_list+=("$i - ${ip_addr%%/*}")
        fi
    done
    # Fetch IPV6 addresses of all network interfaces except docker, loopback, veth, tun, tap,tailscale and bridge interfaces
    for i in $(ip -o -6 addr show | awk '{print $2}' | uniq); do
        if [[ "$i" != docker* ]] && [[ "$i" != lo* ]] && [[ "$i" != veth* ]] && [[ "$i" != flannel* ]] &&
            [[ "$i" != tun* ]] && [[ "$i" != tap* ]] && [[ "$i" != "br-*" ]] && [[ "$i" != cni* ]] && [[ "$i" != tailscale* ]]; then
            ip_addr=$(ip -o -6 addr show "$i" | awk '{print $4}' | head -n1)
            # Trim the Cidr notation suffix /24 from the IP address
            interface_list+=("$i - ${ip_addr%%/*}")
        fi
    done
    # Auto-select the first IP address from the list
    if [[ $auto_select_external_ip == "true" ]]; then
        selected_entry=${interface_list[0]}
        EXTERNAL_IP=$(echo "$selected_entry" | awk '{print $3}')
        EXTERNAL_IP_INTERFACE=$(echo "$selected_entry" | awk '{print $1}')
        EXTERNAL_IP_GATEWAY=$(ip route show dev "$EXTERNAL_IP_INTERFACE" | grep default | awk '{print $3}')
        echo "Auto-selected IP: $EXTERNAL_IP"
        return
    fi
    # Ask user for the external IP address by providing choice from list_network_interfaces_ips
    handleInfo "Select the external IP address of the machine: "
    for i in "${!interface_list[@]}"; do
        echo "$((i + 1))) ${interface_list[$i]}"
    done
    # Provide an option to manually enter the IP address
    echo "$((${#interface_list[@]} + 1))) Enter IP address manually"
    sleep 1

    choice=$(validate_numeric_input "Please select an option (1-$((${#interface_list[@]} + 1))) [default choice: 1]: " 1 $((${#interface_list[@]} + 1)) 1 "$SILENT")

    if [ -z "$choice" ]; then
        ## default choice
        selected_entry=${interface_list[0]} # default select the first network
        EXTERNAL_IP=$(echo "$selected_entry" | awk '{print $3}')
        EXTERNAL_IP_INTERFACE=$(echo "$selected_entry" | awk '{print $1}')
        EXTERNAL_IP_GATEWAY=$(ip route show dev "$EXTERNAL_IP_INTERFACE" | grep default | awk '{print $3}')
        echo "You selected IP: $EXTERNAL_IP"
    elif [ "$choice" -ge 1 ] && [ "$choice" -le "${#interface_list[@]}" ]; then
        # Extract the selected IP address
        selected_entry=${interface_list[$((choice - 1))]}
        EXTERNAL_IP=$(echo "$selected_entry" | awk '{print $3}')
        EXTERNAL_IP_INTERFACE=$(echo "$selected_entry" | awk '{print $1}')
        EXTERNAL_IP_GATEWAY=$(ip route show dev "$EXTERNAL_IP_INTERFACE" | grep default | awk '{print $3}')
        echo "You selected IP: $EXTERNAL_IP"
    elif [ "$choice" -eq "$((${#interface_list[@]} + 1))" ]; then
        # Ask the user to enter the IP address manually
        read -r -p "❓ Please enter the External IP address manually: " EXTERNAL_IP
        EXTERNAL_IP_GATEWAY=$(ip route | grep default | awk '{print $3}')
        # External IP device interface is unknown for this case
        if [[ -z "$EXTERNAL_IP" ]]; then
            handleWarning "You entered an empty IP address. External IP address is required."
            read -r -p "❓ Do you want to provide the external IP address again? (Y/n): " confirm
            if [[ $confirm =~ ^[Yy]$ ]]; then
                ask_external_ip
            else
                return
            fi
        fi
    fi
}

validate_external_ip() {
    ipv4_format="^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$"
    # ipv6_format regex would match only the canonical format recommended by IETF
    # see https://en.wikipedia.org/wiki/IPv6_address#Representation
    ipv6_format="^([0-9a-fA-F]{0,4}:){1,7}[0-9a-fA-F]{0,4}$"
    if [[ -n "$EXTERNAL_IP" ]]; then
        # check for valid ipv4 address
        if [[ $EXTERNAL_IP =~ $ipv4_format ]]; then
            handleInfo "Valid IPv4 address: $EXTERNAL_IP"
        elif [[ $EXTERNAL_IP =~ $ipv6_format ]]; then
            handleInfo "Valid IPv6 address: $EXTERNAL_IP"
        else
            read -r -p "❓ The provided IP address $EXTERNAL_IP is not valid. Do you want to provide the external IP address again? (Y/n): " confirm
            confirm=${confirm:-Y}
            if [[ ! $confirm =~ ^[Yy]$ ]]; then
                return
            else
                ask_external_ip
                validate_external_ip
            fi
        fi

    fi
}

# Function to check if a DNS server is working properly
check_dns_server() {
    local dns_server="$1"
    handleCheck "Testing DNS server $dns_server..."
    # First check if the server supports IPv4
    if ! dig +short -4 management.umh.app @"$dns_server" >/dev/null 2>&1; then
        handleWarning "DNS server $dns_server does not support IPv4"
        return 1
    fi

    # Then check if the server supports recursive queries (RA flag)
    handleCheck "Testing if DNS server supports recursive queries..."
    if ! dig +noall +comments @"$dns_server" -4 management.umh.app | grep -q "flags:.*ra.*"; then
        handleWarning "DNS server $dns_server does not support recursive queries (no RA flag), which are required for Kubernetes to work properly"
        return 1
    fi

    # Test recursive resolution and management.umh.app resolution
    # +time=1 sets timeout to 3 seconds
    # +tries=2 sets number of retries to 2
    if ! dig +short +time=1 +tries=2 @"$dns_server" -4 management.umh.app >/dev/null 2>&1; then
        handleWarning "DNS server $dns_server cannot find our services (failed to resolve management.umh.app), this could mean the DNS server is not working properly or is blocked by a firewall"
        return 1
    fi

    handleSuccess "DNS server $dns_server is working properly and can find our services"
    return 0
}

# Function to validate a single DNS server
validate_dns_server() {
    local dns_server="$1"

    # Check if input is a valid IPv4 address (reject IPv6)
    if ! [[ $dns_server =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
        handleWarning "The address '$dns_server' is not a valid IPv4 address"
        handleInfo "IPv6 DNS servers are currently not supported. Please provide an IPv4 address in the format: xxx.xxx.xxx.xxx (like 8.8.8.8 for Google DNS)"
        return 1
    fi

    # Check DNS server functionality
    check_dns_server "$dns_server" || return 1

    return 0
}

# Function to modify CoreDNS configuration
modify_coredns_config() {
    local dns_servers=("$@")
    handleStep "Modifying CoreDNS configuration..."

    # Create backup of original Corefile
    if ! $KUBECTL_PATH -n kube-system get configmap coredns -o yaml > "$TEMP_DIR/coredns-backup.yaml"; then
        handleError "Failed to backup DNS settings" "This could mean your system isn't running properly. Try restarting and running the installer again."
        return 1
    fi

    if ! $KUBECTL_PATH -n kube-system get configmap coredns -o jsonpath='{.data.Corefile}' > "$TEMP_DIR/original-corefile"; then
        handleError "Failed to extract current Corefile" "This could mean your CoreDNS ConfigMap is corrupted."
        return 1
    fi

    # Prepare the forward configuration
    local forward_servers=""
    for server in "${dns_servers[@]}"; do
        forward_servers+=" $server"
    done
    
    
    # Update only the forward directive using sed
    # This assumes the forward directive is on a single line
    if grep -q "forward\s\." "$TEMP_DIR/original-corefile"; then
        # Update existing forward directive
        sed -i "s|forward \.[^}]*|forward .${forward_servers}|g" "$TEMP_DIR/original-corefile"
    else
        # Add forward directive before the closing bracket of the main block
        sed -i "/prometheus :9153/a\\    forward .${forward_servers}" "$TEMP_DIR/original-corefile"
    fi

    if ! $KUBECTL_PATH -n kube-system create configmap coredns --from-file=Corefile="$TEMP_DIR/original-corefile" -o yaml --dry-run=client | $KUBECTL_PATH apply -f -; then
        handleError "Failed to update CoreDNS configuration" "Check if CoreDNS is running properly"
        # Restore the backup in case of failure
        $KUBECTL_PATH apply -f "$TEMP_DIR/coredns-backup.yaml" || handleWarning "Failed to restore CoreDNS backup"
        return 1
    fi

    # Restart CoreDNS pods to apply new DNS settings
    handleStep "Applying the new DNS settings..."
    retry_count=0
    max_retries=5
    success=false
    
    while [ $retry_count -lt $max_retries ] && [ "$success" = "false" ]; do

        if ! $KUBECTL_PATH -n kube-system rollout restart deployment/coredns; then
            handleWarning "Failed to initiate CoreDNS rollout"
            retry_count=$((retry_count + 1))
            sleep 1
            continue
        fi

        if $KUBECTL_PATH -n kube-system rollout status deployment/coredns --timeout=60s; then
            handleSuccess "CoreDNS configuration updated and pods restarted successfully"
            success=true
        else
            handleWarning "CoreDNS rollout started but couldn't confirm completion"
            # The rollout status is stuck at this point. Let's force delete coredns pods
            if $KUBECTL_PATH -n kube-system delete pods -l k8s-app=kube-dns --grace-period=0 --force; then
                success=true
            fi
        fi
        
        if [ "$success" = "false" ]; then
            retry_count=$((retry_count + 1))
            if [ $retry_count -lt $max_retries ]; then
                backoff=$((2 ** (retry_count - 1)))
                handleWarning "Retry $retry_count/$max_retries: Retrying CoreDNS restart in ${backoff}s..."
                sleep $backoff
            fi
        fi
    done

    if [ "$success" = "false" ]; then
        handleError "Failed to restart CoreDNS pods after $max_retries attempts" "Check if CoreDNS is running properly"
        return 1
    fi

    handleSuccess "CoreDNS configuration updated successfully"
    return 0
}

# Function to configure DNS with custom servers
configure_dns() {
    # If CUSTOM_DNS_SERVERS is set, use non-interactive mode
    if [[ -n "$CUSTOM_DNS_SERVERS" ]]; then
        handleInfo "Using the DNS servers you provided: $CUSTOM_DNS_SERVERS"

        # Convert comma-separated string to array
        DEFAULT_IFS=$IFS
        IFS=',' read -ra dns_servers <<< "$CUSTOM_DNS_SERVERS"
        IFS=$DEFAULT_IFS
        # Validate each DNS server
        for server in "${dns_servers[@]}"; do
            # Trim whitespace
            server=$(echo "$server" | tr -d '[:space:]')
            if ! validate_dns_server "$server"; then
                handleError "Custom DNS server $server validation failed" "Please check your CUSTOM_DNS_SERVERS configuration. Only IPv4 addresses are supported."
            fi
        done

        # Validate that we have at max 3 custom DNS servers
        if [ ${#dns_servers[@]} -gt 3 ]; then
            handleError "You can only have at max 3 custom DNS servers" "Please check your CUSTOM_DNS_SERVERS configuration"
        fi

        # If we get here, all servers are valid - modify CoreDNS config
        modify_coredns_config "${dns_servers[@]}"
        return
    fi

    local custom_dns_servers=()
    local dns_check_failed=false

    # Check if system DNS resolution works
    handleCheck "Testing if your system can find our services..."

    if ! dig +short +time=1 +tries=2 -4 management.umh.app >/dev/null 2>&1; then
        handleWarning "Your system is having trouble finding our services with its current settings"
        handleInfo "We'll help you set up alternative DNS servers to fix this"
        dns_check_failed=true
    else
        # Check for RA flag
        if ! dig +noall +comments -4 management.umh.app | grep -q "flags:.*ra.*"; then
            handleWarning "Your system's DNS server might have limited functionality"
            handleInfo "We recommend setting up alternative DNS servers for better reliability"
            dns_check_failed=true
        fi
    fi

    # Ask user if they want to configure custom DNS servers
    local configure_custom_dns="n"
    if [ "$dns_check_failed" = true ]; then
        handleWarning "System DNS resolution failed. Kubernetes might not work properly without manual DNS configuration."
        handleInfo "Your DNS server does not support recursive queries (no RA flag) or is not working properly."
        handleInfo "If you are unsure about which DNS server to use, please contact your network administrator and provide the following information:"
        handleInfo "1. The name or IP address of your server"
        handleInfo "2. The following output of the dig command:"
        handleInfo "================================================"
        (dig +comments +time=1 -4 management.umh.app || true)
        handleInfo "================================================"
        handleInfo "You can also try to use a public DNS server like Google DNS (8.8.8.8 and 8.8.4.4) or Cloudflare DNS (1.1.1.1 and 1.0.0.1)."
    else
        handleInfo "System DNS resolution works properly. No need to configure custom DNS servers."
    fi
    if [ "$dns_check_failed" = false ]; then
        read -r -p "❓ Do you want to configure custom DNS servers for Kubernetes? (y/N): " configure_custom_dns
    else
        configure_custom_dns="y"
    fi

    if [[ $configure_custom_dns =~ ^[Yy]$ ]]; then
        while true; do
            custom_dns_servers=()
            local server_count
            server_count=0
            handleInfo "You can add up to 3 DNS servers"
            handleInfo "Popular options include:"
            handleInfo "- Google DNS: 8.8.8.8 and 8.8.4.4"
            handleInfo "- Cloudflare: 1.1.1.1 and 1.0.0.1"

            while [ $server_count -lt 3 ]; do
                # List all currently added DNS servers
                if [ ${#custom_dns_servers[@]} -gt 0 ]; then
                    echo "Currently added DNS servers:"
                    for server in "${custom_dns_servers[@]}"; do
                        echo " - $server"
                    done
                fi
                read -r -p "❓ Enter IPv4 DNS server (e.g. 8.8.8.8) [at least one required, press Enter when done]: " dns_server

                # Allow breaking if at least one server is configured
                if [ -z "$dns_server" ] && [ ${#custom_dns_servers[@]} -gt 0 ]; then
                    handleSuccess "Configuration complete with ${#custom_dns_servers[@]} DNS server(s)"
                    break
                elif [ -z "$dns_server" ]; then
                    handleWarning "You entered an empty DNS server. Please try again."
                    continue
                fi

                if validate_dns_server "$dns_server"; then
                    custom_dns_servers+=("$dns_server")
                    server_count=$((server_count + 1))
                else
                    handleWarning "DNS server validation failed. Please try again."
                    continue
                fi
            done

            # If at least one custom DNS server was added successfully
            if [ ${#custom_dns_servers[@]} -gt 0 ]; then
                modify_coredns_config "${custom_dns_servers[@]}"
                break
            else
                handleWarning "No valid DNS servers provided. Using system defaults."
                break
            fi
        done
    else
        handleSuccess "Continuing with your current DNS settings"
    fi

    # Set DNS_SERVER variable to our custom DNS servers (if any) [comma separated list]
    if [ ${#custom_dns_servers[@]} -gt 0 ]; then
        local dns_servers_string
        DEFAULT_IFS=$IFS
        IFS=','
        dns_servers_string="${custom_dns_servers[*]}"
        IFS=$DEFAULT_IFS
        export DNS_SERVER=$dns_servers_string
    else
        # Gather default dns server from dig (;; SERVER: ...)
        local default_dns_server
        default_dns_server=$(dig management.umh.app | grep -oP ';;\s*SERVER:\s*\K\S+(?=#)')
        export DNS_SERVER=$default_dns_server
    fi
}


##########################################################################################
#                       Tool Installation and Verification                               #
# This section includes functions for installing key tools (kubectl, helm) and          #
# verifying the installation of required tools. It handles installations for specific    #
# systems (like RHEL) and general systems, and sets the path for each tool.             #
##########################################################################################

# --- Install kubectl ---
install_kubectl() {
    local kubectl_target="/usr/local/bin/kubectl"
    if [[ "$OS" == "flatcar" ]]; then
        kubectl_target="/opt/bin/kubectl"
    fi

    # Declare the variable separately
    local current_version

    # Check if kubectl is already installed and check its version
    if [[ -x "$kubectl_target" ]]; then
        # Check if kubectl_target is a real binary file using file command
        if ! file "$kubectl_target" | grep -q "ELF"; then
            # Delete it
            handleWarning "The local kubectl binary is corrupted, deleting it..."
            rm -f "$kubectl_target"
        else
            current_version=$("$kubectl_target" version --client --output=json | jq -r ".clientVersion.gitVersion" 2>/dev/null)
            echo "Current installed kubectl version: $current_version"
            if [[ "$current_version" == "$INSTALL_KUBECTL_VERSION" ]]; then
                echo "kubectl version $INSTALL_KUBECTL_VERSION is already installed."
                export KUBECTL_PATH="$kubectl_target"
                return 0 # Exit the function if the installed version matches the desired version
            fi
            echo "Having an incompatible version might lead to errors during the installation"
            export KUBECTL_PATH="$kubectl_target"
            return 0 # Exit the function if kubectl is already installed but with a different version
        fi
    fi

    if ! downloadFile "${CUSTOM_MGMT_URL}/binaries/kubectl/$INSTALL_KUBECTL_VERSION/bin/linux/amd64/kubectl" "$TEMP_DIR/kubectl"; then
        handleError "Failed to download kubectl." "Check your network connection."
        return
    fi
    if ! mv "$TEMP_DIR/kubectl" "$kubectl_target" 2>&1 | tee -a "$TEMP_DIR/mgmt_install.log" >/dev/null; then
        handleError "Failed to move kubectl to $kubectl_target." "Check file permissions."
        return
    fi
    if ! chmod +x "$kubectl_target" | tee -a $TEMP_DIR/mgmt_install.log >/dev/null; then
        handleError "Failed to make kubectl executable." "Check file permissions."
        return
    fi
    handleSuccess "kubectl installed successfully at $kubectl_target."
    export KUBECTL_PATH="$kubectl_target"
}

uninstall_kubectl() {
    local kubectl_binary="kubectl"
    if [[ "$OS" == "flatcar" ]]; then
        kubectl_binary="/opt/bin/kubectl"
    fi

    local kubectl_path
    kubectl_path=$(which "$kubectl_binary" 2>/dev/null || true)

    if [ -n "$kubectl_path" ]; then
        handleStep "Removing kubectl binary at $kubectl_path"
        rm -f "$kubectl_path" || true
    else
        handleWarning "kubectl binary not found. Skipping kubectl removal."
    fi
}

# --- Install helm ---
install_helm() {

    if [[ "$OS" == "flatcar" ]]; then
        export HELM_INSTALL_DIR="/opt/bin"
    fi

    if ! downloadFile "${CUSTOM_MGMT_URL}/binaries/helm/get-helm-3" "$TEMP_DIR/get_helm.sh"; then
        handleError "Failed to download get_helm.sh." "Check your network connection."
        return
    fi
    if ! chmod 700 $TEMP_DIR/get_helm.sh >>$TEMP_DIR/mgmt_install.log 2>&1; then
        handleError "Failed to make get_helm.sh executable." "Check file permissions."
        return
    fi

    local helm_install_cmd="$TEMP_DIR/get_helm.sh"

    if ! $helm_install_cmd --version "$INSTALL_HELM_VERSION" >>$TEMP_DIR/mgmt_install.log 2>&1; then
        handleError "Failed to install helm." "Check logs for error details."
        return
    fi
    handleSuccess "helm installed successfully."
    HELM_PATH=$(which helm)
    export HELM_PATH
}

uninstall_helm() {
    local helm_binary="helm"
    if [[ "$OS" == "flatcar" ]]; then
        helm_binary="/opt/bin/helm"
    fi

    local helm_path
    helm_path=$(which "$helm_binary" 2>/dev/null || true)

    handleCheck "Checking Helm binary..."
    if [ -n "$helm_path" ]; then
        handleStep "Helm binary found at $helm_path. Proceeding with removal."

        # Remove Helm repositories
        handleStep "Removing Helm repositories"
        if "$helm_path" repo list 2>/dev/null | grep -q 'united-manufacturing-hub'; then
            "$helm_path" repo remove united-manufacturing-hub || true
        fi

        # Remove Helm binary
        handleStep "Removing Helm binary"
        rm -f "$helm_path" || true

    else
        handleWarning "Helm binary not found. Skipping Helm removal."
    fi
}

# --- RHEL-specific installation, but kubectl and Helm are never installed via yum, only the base tools like dig, curl, etc. ---
install_rhel() {
    local tool_name=$1
    local package_name

    case $tool_name in
    dig) package_name="bind-utils" ;;
    curl) package_name="curl" ;;
    jq) package_name="jq" ;;
    tar) package_name="tar" ;;
    *)
        handleError "Tool $tool_name is not recognized." "Please contact us for support."
        return
        ;;
    esac

    handleCheck "Installing $tool_name on RHEL..."
    # Try to install up to five times
    installed=false
    for _ in {1..5}; do
        if ! yum install -y $package_name >>$TEMP_DIR/mgmt_install.log 2>&1; then
            handleWarning "Failed to install $tool_name. Retrying in 5 seconds..."
        else
            handleSuccess "$tool_name installed successfully."
            installed=true
            break
        fi
    done
    if [[ $installed == false ]]; then
        handleError "Failed to install $tool_name." "Check your network connection or install $tool_name manually."
    fi
}

# --- apt-specific installation (Ubuntu) ---
install_apt() {
    local tool_name=$1
    local package_name

    # Ensure apt is recently updated
    handleStep "Updating apt..."
    if ! apt-get update -y >>$TEMP_DIR/mgmt_install.log 2>&1; then
        handleError "Failed to update apt." "Check your network connection."
    fi
    handleSuccess "apt updated successfully."

    case $tool_name in
    dig) package_name="dnsutils" ;;
    curl) package_name="curl" ;;
    jq) package_name="jq" ;;
    tar) package_name="tar" ;;
    *)
        handleError "Tool $tool_name is not recognized." "Please contact us for support."
        return
        ;;
    esac

    handleCheck "Installing $tool_name on $OS..."
    # Try to install up to five times
    installed=false
    for _ in {1..5}; do
        if ! apt-get install -y $package_name >>$TEMP_DIR/mgmt_install.log 2>&1; then
            handleWarning "Failed to install $tool_name. Retrying in 5 seconds..."
        else
            handleSuccess "$tool_name installed successfully."
            installed=true
            break
        fi
    done
    if [[ $installed == false ]]; then
        handleError "Failed to install $tool_name." "Check your network connection or install $tool_name manually."
    fi
}

# --- Generic installation for non-RHEL systems ---
install_generic() {
    local tool_name=$1

    case $tool_name in
    *)
        handleError "Tool $tool_name is not recognized." "Please ensure the tool is installed manually."
        return
        ;;
    esac
}

# --- Check and Set Path for Tools ---
check_and_set_path() {
    local var_name=$1
    local tool_name=$2
    handleCheck "Checking if $tool_name is installed..."

    # Use default expansion to handle potentially unset variables
    local current_path="${!var_name:-}"

    if [ -z "$current_path" ]; then
        local tool_path
        if ! tool_path=$(which "$tool_name"); then
            case $OS in
            "rhel" | "rocky")
                install_rhel "$tool_name"
                ;;
            "ubuntu")
                install_apt "$tool_name"
                ;;
            *)
                install_generic "$tool_name"
                ;;
            esac
            # Now try again to get the path
            if ! tool_path=$(which "$tool_name"); then
                handleError "Failed to install $tool_name." "Check your network connection or install $tool_name manually."
            fi
            # Set the path
            handleSuccess "$tool_name is installed at: $tool_path"
            export "$var_name"="$tool_path"
        else
            handleSuccess "$tool_name is installed at: $tool_path"
            export "$var_name"="$tool_path"
        fi
    else
        handleWarning "$var_name is overwritten to: $current_path"
    fi
}

# Function to patch the rocky linux yum repository
patch_rocky(){
  # If not rocky, return
  if [[ $OS != "rocky" ]]; then
    handleInfo "Not a Rocky Linux system. Skipping patching of yum repository."
    return
  fi

  handleInfo "Patching yum repository for Rocky Linux..."

  # Backup all files in /etc/yum.repos.d to /etc/yum.repos.d.backup
  if [[ ! -d /etc/yum.repos.d.backup ]]; then
    mkdir /etc/yum.repos.d.backup
    cp /etc/yum.repos.d/* /etc/yum.repos.d.backup
  fi

  # Remove all files in /etc/yum.repos.d
  rm -f /etc/yum.repos.d/*

  # Add our own repository file (for baseos, appstream, extras)
  cat <<EOF > /etc/yum.repos.d/umh-rocky.repo
[rocky-custom-baseos]
name=Rocky Linux Custom BaseOS
baseurl=https://management.umh.app/mirror/rockylinux/REPLACEMEROCKYWITHMINORVERSION/BaseOS/\$basearch/os/
enabled=1
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-Rocky-REPLACEMEROCKYVERSION

[rocky-custom-appstream]
name=Rocky Linux Custom AppStream
baseurl=https://management.umh.app/mirror/rockylinux/REPLACEMEROCKYWITHMINORVERSION/AppStream/\$basearch/os/
enabled=1
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-Rocky-REPLACEMEROCKYVERSION

[rocky-custom-extras]
name=Rocky Linux Custom Extras
baseurl=https://management.umh.app/mirror/rockylinux/REPLACEMEROCKYWITHMINORVERSION/extras/\$basearch/os/
enabled=1
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-Rocky-REPLACEMEROCKYVERSION
EOF
  # Get the version of Rocky
  ROCKY_VERSION=$(cat /etc/redhat-release | grep -oP '\d' | head -1)
  ROCKY_VERSION_WITH_MINOR=$(cat /etc/redhat-release | grep -oP '\d\.\d' | head -1)
  handleInfo "Rocky Linux version: $ROCKY_VERSION"
  handleInfo "Rocky Linux version with minor: $ROCKY_VERSION_WITH_MINOR"

  # Replace REPLACEMEROCKYVERSION in file with either 8 or 9 (depending on the version of Rocky)
  sed -i "s/REPLACEMEROCKYVERSION/$ROCKY_VERSION/g" /etc/yum.repos.d/umh-rocky.repo

  # Replace REPLACEMEROCKYWITHMINORVERSION in file with either 9.X (if Rocky 9) or 8.X (if Rocky 8)
  sed -i "s/REPLACEMEROCKYWITHMINORVERSION/$ROCKY_VERSION_WITH_MINOR/g" /etc/yum.repos.d/umh-rocky.repo

  # Recreate dnf cache
  handleStep "Recreating dnf cache..."
  dnf clean all
  handleStep "Recreating dnf cache..."
  dnf makecache

  handleSuccess "Patched yum repository for Rocky Linux."
}

# Function to verify and set paths for required tools
verify_and_set_tool_paths() {
    handleCheck "Verifying installation of all required tools..."

    # Check and set path for basic utilities
    check_and_set_path DIG_PATH dig
    check_and_set_path CURL_PATH curl
    check_and_set_path JQ_PATH jq
    check_and_set_path SED_PATH sed
    check_and_set_path BASE64_PATH base64
    check_and_set_path TAR_PATH tar

    handleSuccess "Verification complete: All required tools are installed and configured."
}

downloadFile() {
    local url="$1"
    local target="$2"
    local retries=5

    local CURL_PATH="$CURL_PATH --connect-timeout 10 --retry 5 --retry-delay 5 --retry-max-time 60 --retry-connrefused --retry-all-errors -sSL"
    local CURL_WITH_RESUME="$CURL_PATH -C - "

    # First try without resume capability
    if $CURL_PATH $url -o $target >>$TEMP_DIR/mgmt_install.log 2>&1; then
        return 0
    fi
    handleWarning "Failed to download $url. Retrying with resume support..."

    for i in $(seq 1 "$retries"); do
        if $CURL_WITH_RESUME $url -o $target >>$TEMP_DIR/mgmt_install.log 2>&1; then
            return 0
        fi
        handleWarning "Failed to download $url. Attempt $i of $retries. Retrying in 5 seconds..."
        sleep 5
    done
    handleError "Failed to download $url." "Check your network connection."
    return 1
}

##########################################################################################
#                            Kubernetes (k3s + kubectl) Installation                     #
# This section of the script focuses on installing Kubernetes, specifically k3s and      #
# kubectl. It performs prerequisite checks, applies configurations tailored for RHEL     #
# (like firewall settings) as well as generic systems, and executes the installation     #
# process for both k3s and kubectl. The script also handles TLS certificate setup,       #
# configures kubelet, and ensures that all installations align with system requirements. #
##########################################################################################

# Function to perform initial checks and preparations
perform_initial_checks() {

    # Summary of changes to be done #600
    handleCheck "This script will perform the following actions on your system:"
    handleInfo "1️⃣ Check for necessary prerequisites."
    handleInfo "2️⃣ Install k3s and kubectl if not already installed."
    handleInfo "3️⃣ Use $INSTALL_K3S_EXEC as tls-san."
    handleInfo "4️⃣ Install or overwrite MgmtCompanion."

    # Step 5-7 only on rhel or similar (rocky)
    if [[ $OS == "rhel" ]] || [[ $OS == "rocky" ]]; then
        handleInfo "5️⃣ Disable the firewall."
        handleInfo "6️⃣ Install SELinux policy for k3s."
        handleInfo "7️⃣ Disable nm-cloud-setup.service."
    fi
    if [[ $skip_umh_install == false ]]; then
        handleInfo "8️⃣ Install UMH."
    fi

    handleStep "Beginning installation..."

    if [[ -z "$KUBECONFIG" ]] && [[ ! -f "$KUBECONFIG" ]]; then
        handleError "KUBECONFIG environment variable is not set or file not found." "Set the KUBECONFIG environment variable to the correct path."
    fi
    handleStep "KUBECONFIG file found at: $KUBECONFIG"
}

# Switch based on detected os (generic or rhel)

function pre_install_generic() {
    handleStep "Running generic pre-installation steps..."

    handleSuccess "Generic pre-installation steps are completed successfully."
}

function pre_install_rhel() {
    handleStep "Running RHEL pre-installation steps..."

    # Disable nm-cloud-setup.service
    handleCheck "Checking if nm-cloud-setup.service is enabled..."
    if systemctl list-units --full --all | grep -Fq 'nm-clouud-setup.service'; then
        handleStep "nm-cloud-setup.service is enabled. Disabling nm-cloud-setup.service..."
        if ! systemctl disable --now nm-cloud-setup.service >>$TEMP_DIR/mgmt_install.log 2>&1; then
            handleError "Failed to disable nm-cloud-setup.service." "Manually disable nm-cloud-setup.service using 'sudo systemctl disable --now nm-cloud-setup.service' and run the script again."

        fi
        handleSuccess "nm-cloud-setup.service is disabled successfully."
    else
        handleSuccess "nm-cloud-setup.service is already disabled."
    fi

    # The install script shall disable the firewall for RHEL/CentOS/Fedora as per k3s documentation
    handleSecurity "Checking and disabling the firewall..."
    if systemctl list-unit-files --type=service --no-pager | grep -Fq 'firewalld.service'; then
        if ! systemctl disable --now firewalld; then
            handleError "Failed to disable the firewall." "Manually disable the firewall using 'sudo systemctl disable --now firewalld' and run the script again."

        fi
        handleSuccess "Firewall disabled successfully."
    elif systemctl list-units --full --all | grep -Fq 'firewalld.service'; then
        if ! systemctl disable --now firewalld; then
            handleError "Failed to disable the firewall." "Manually disable the firewall using 'sudo systemctl disable --now firewalld' and run the script again."

        fi
        handleSuccess "Firewall disabled successfully."
    elif systemctl disable --now firewalld; then
        handleSuccess "Firewall disabled successfully."
    else
        handleWarning "Firewalld service not found. Skipping firewall disable step."
    fi
    handleSuccess "Firewall disabled successfully."

    handleSuccess "RHEL pre-installation steps are completed successfully."
}

# Drop the /etc/rancher/k3s/registries.yaml file to overwrite the default registry
patch_registry() {
    #  mirrors:
    #    "docker.io":
    #      endpoint:
    #        - "https://management.umh.app/oci"

    handleStep "Patching registries.yaml to use management.umh.app as the default registry..."
    local registries_file="/etc/rancher/k3s/registries.yaml"
    local registries_dir="/etc/rancher/k3s"

    if ! mkdir -p "$registries_dir" >>$TEMP_DIR/mgmt_install.log 2>&1; then
        handleError "Failed to create directory $registries_dir." "Check file permissions."
    fi

    # Download the registries.yaml file if it does not exist
    if ! downloadFile "$REGISTRIES_URL" "$registries_file"; then
        handleError "Failed to download registries.yaml." "Check your network connection and try again."
    fi

    handleSuccess "registries.yaml patched successfully."
}

# Function to check if the node is tainted
is_node_tainted() {
    $KUBECTL_PATH get node -o json | jq -e '.spec.taints | length > 0' >>$TEMP_DIR/mgmt_install.log 2>&1
}

# Wait for node to not have any taints
wait_for_node_ready() {
    # Give it up to 5 minutes to be ready (check every second)
    handleStep "Waiting for node to be ready..."
    for _ in {1..300}; do
        if ! is_node_tainted; then
            handleSuccess "Node is ready."
            return
        fi
        sleep 1
    done
    handleError "Node is not ready." "Please contact our support team."
}

# Function to install k3s
install_k3s() {
    # Check if k3s needs to be installed
    # The install script shall check if k3s is installed, and if not install it #575
    handleCheck "Checking for k3s..."

    if command -v k3s &>/dev/null; then
        handleWarning "Existing k3s installation detected."
        if [[ "$SILENT" == "true" ]]; then
            uninstall_choice="y"
            handleInfo "Silent mode: automatically uninstalling existing k3s installation"
        else
            read -r -p "❓ Do you want to uninstall the existing k3s installation? (Y/n): " uninstall_choice
            uninstall_choice=${uninstall_choice:-Y}
        fi

        if [[ $uninstall_choice =~ ^[Yy]$ ]]; then
            handleCheck "Uninstalling K3s..."
            if [ -f /usr/local/bin/k3s-uninstall.sh ]; then
                # Stop K3s service
                manage_k3s_service "stop" || true

                /usr/local/bin/k3s-uninstall.sh >/dev/null 2>>$TEMP_DIR/k3s_uninstall.log
                uninstall_status=$?

                # Remove the K3s containerd container blobs so that the new installation starts from scratch
                # The container blobs creates problems sometimes during the new installation
                rm -rf /var/lib/rancher/k3s/agent/containerd/io.containerd.content.v1.content/blobs/
            else
                handleWarning "k3s-uninstall.sh not found."
                uninstall_status=1
            fi

            if [ ${uninstall_status} -eq 0 ]; then
                handleSuccess "K3s has been successfully uninstalled."
            else
                handleWarning "Failed to uninstall K3s. Existing K3s installation will be used."
            fi
        else
            handleInfo "Keeping existing k3s installation."
        fi
    fi

    if ! command -v k3s >>$TEMP_DIR/mgmt_install.log 2>&1 || [[ ! -f $KUBECONFIG ]]; then
        handleWarning "k3s is not installed or KUBECONFIG file does not exist" >>$TEMP_DIR/mgmt_install.log
        handleInfo "Installing k3s with args: $INSTALL_K3S_EXEC" >>$TEMP_DIR/mgmt_install.log

        if [ "$OS" = "rhel" ] || [ "$OS" = "rocky" ]; then
            if [[ "$SKIP_RHEL_SHA1_SIGNATURES" == "false" ]]; then
                handleStep "Allowing SHA1 package signatures..."
                if ! update-crypto-policies --set DEFAULT:SHA1 >>$TEMP_DIR/mgmt_install.log 2>&1; then
                    handleError "Failed to allow SHA1 package signatures." "Manually allow SHA1 package signatures using 'sudo update-crypto-policies --set DEFAULT:SHA1' and run the script again."
                fi
                handleSuccess "SHA1 package signatures are allowed."
            else
                handleWarning "Skipping SHA1 package signatures allowance as SKIP_RHEL_SHA1_SIGNATURES is set."
            fi
        fi
        if ! downloadFile "${CUSTOM_MGMT_URL}/binaries/k3s/get-k3s.sh" "$TEMP_DIR/k3s-install.sh"; then
            handleError "Failed to download k3s-install.sh." "Check your network connection and try again."
        fi
        if ! chmod +x "$TEMP_DIR/k3s-install.sh" >>$TEMP_DIR/mgmt_install.log 2>&1; then
            handleError "Failed to make k3s-install.sh executable." "Check the file permissions and try again."
        fi
        # Execute this before installing k3s to skip a restart
        patch_registry
        local retry_count=0
        local max_retries=5
        local success=false
        
        while [ $retry_count -lt $max_retries ] && [ "$success" = "false" ]; do
            if bash "$TEMP_DIR/k3s-install.sh" | tee -a $TEMP_DIR/mgmt_install.log 2>&1; then
                success=true
            else
                retry_count=$((retry_count + 1))
                if [ $retry_count -lt $max_retries ]; then
                    handleWarning "Failed to install k3s (attempt $retry_count/$max_retries). Retrying in 10 seconds..."
                    sleep 10
                fi
            fi
        done
        
        if [ "$success" = "false" ]; then
            handleError "Failed to install k3s after $max_retries attempts" "Check the logs for error details."
        fi
        if ! rm "$TEMP_DIR/k3s-install.sh" >>$TEMP_DIR/mgmt_install.log 2>&1; then
            handleError "Failed to remove k3s-install.sh." "Check the file permissions and try again."
        fi
        if [ "$OS" = "rhel" ] || [ "$OS" = "rocky" ]; then
            if [[ "$SKIP_RHEL_SHA1_SIGNATURES" == "false" ]]; then
                handleStep "Returning back to the default crypto policy..."
                if ! update-crypto-policies --set DEFAULT >>$TEMP_DIR/mgmt_install.log 2>&1; then
                    handleError "Failed to return back to the default crypto policy." "Manually return back to the default crypto policy using 'sudo update-crypto-policies --set DEFAULT' and run the script again."
                fi
            fi
        fi
        handleSuccess "k3s is installed successfully."
        wait_for_node_ready
    else
        handleSuccess "k3s is already installed."
    fi
}

# Function to get IP addresses of all real network interfaces
function get_ip_addresses {
    # Check if ip command is available, if not, return
    if ! command -v ip >>$TEMP_DIR/mgmt_install.log 2>&1; then
        return
    fi

    ip_addresses=$(ip -o addr show up primary scope global | grep -vE '^[0-9]+: (flannel|cni|docker|veth|br-|virbr|tun|tap|lo)' | awk '{gsub(/\/.*/,"",$4); print $4}')
    echo "$ip_addresses" >>$TEMP_DIR/mgmt_install.log 2>&1
    echo "$ip_addresses"
}

# Setting up INSTALL_K3S_EXEC with the IP addresses as tls-san
function setup_tls_san {
    ip_addresses=$(get_ip_addresses)
    INSTALL_K3S_EXEC=""
    # Check that $ip_addresses is not empty (if it is don't add --tls-san)
    if [[ -z $ip_addresses ]]; then
        handleWarning "No IP addresses found. Skipping tls-san configuration."
        return
    fi
    for ip in $ip_addresses; do
        INSTALL_K3S_EXEC+="--tls-san $ip "
    done

    # Check if CUSTOM_TLS_SAN is set and if so, add it to INSTALL_K3S_EXEC
    if [[ -n $CUSTOM_TLS_SAN ]]; then
        handleStep "Adding $CUSTOM_TLS_SAN to tls-san..."
        INSTALL_K3S_EXEC+="--tls-san $CUSTOM_TLS_SAN "
    fi

    # Add data-dir if specified
    if [[ -n $K3S_DATA_DIR ]]; then
        handleStep "Setting k3s data directory to $K3S_DATA_DIR..."
        INSTALL_K3S_EXEC+="--data-dir $K3S_DATA_DIR "
    fi

    export INSTALL_K3S_EXEC
}

# Function to prepare kubelet configuration
prepare_kubelet_configuration() {

    # Preparing kubelet configuration for custom 'maxPods' setting
    handleStep "Preparing kubelet configuration..."
    # Check if the kubelet config file already exists; if so, reset it to start fresh
    if test -f /opt/kubelet-config.yaml; then
        handleWarning "kubelet-config.yaml already exists. Truncating the file to start fresh."
        truncate -s 0 /opt/kubelet-config.yaml # Truncate existing file for a clean start
    else
        if [ ! -d "/opt" ]; then
            handleInfo "Creating /opt directory."
            mkdir -p /opt # Ensure the /opt directory exists
        else
            handleInfo "/opt directory already exists."
        fi

        touch /opt/kubelet-config.yaml # Create the kubelet config file
    fi

    # Download the kubelet-config.yaml file
    if ! downloadFile "$KUBELET_URL" "/opt/kubelet-config.yaml"; then
        handleError "Failed to download kubelet-config.yaml.yaml." "Check your network connection"
    fi

    # Append the kubelet config to the k3s install command
    # Ensures k3s uses the custom kubelet configuration during installation
    export INSTALL_K3S_EXEC+="--kubelet-arg=config=/opt/kubelet-config.yaml "
    handleSuccess "'maxPods' configured successfully in kubelet. Kubelet configuration is ready."
}

# Function to prepare nodename configuration
prepare_nodename_configuration() {
    # Strip any kind of whitespace, newlines, etc from NODE_NAME
    NODE_NAME=$(echo "$NODE_NAME" | tr -d '[:space:]')

    # Use NODE_NAME to set --node-name flag in k3s install command
    if [[ -n "$NODE_NAME" ]]; then
        handleStep "Setting node name to $NODE_NAME..."
        export INSTALL_K3S_EXEC+="--node-name $NODE_NAME "
        handleSuccess "Node name set to $NODE_NAME."
    else
        handleWarning "NODE_NAME is not set. Skipping node name configuration."
    fi
}

# Check if hostname equals NODE_NAME, and if not ask to overwrite (default/enter is yes)
prepare_hostname() {
    if [[ -n "$NODE_NAME" ]]; then
        if [[ "$NODE_NAME" != "$(hostname)" ]]; then
            # If auto_patch_hostname, skip the prompt and set the hostname to NODE_NAME
            if [[ "$auto_patch_hostname" == "true" ]]; then
                handleStep "Auto-patching hostname to $NODE_NAME..."
                if ! hostnamectl set-hostname "$NODE_NAME"; then
                    handleError "Failed to set hostname to $NODE_NAME." "Check your system configuration."
                fi
                handleSuccess "Hostname patched to $NODE_NAME."
            else
                handleWarning "Hostname ($(hostname)) does not match $NODE_NAME."
                read -r -p "❓ Do you want to set the hostname to $NODE_NAME? (Y/n): " confirm
                confirm=${confirm:-Y}
                if [[ $confirm =~ ^[Yy]$ ]]; then
                    handleStep "Patching hostname to $NODE_NAME..."
                    if ! hostnamectl set-hostname "$NODE_NAME"; then
                        handleError "Failed to set hostname to $NODE_NAME." "Check your system configuration."
                    fi
                    handleSuccess "Hostname patched to $NODE_NAME."
                else
                    handleWarning "Skipping hostname configuration."
                fi
            fi
        else
            handleSuccess "Hostname ($(hostname)) matches $NODE_NAME."
        fi
    else
        handleWarning "NODE_NAME is not set. Skipping hostname configuration."
    fi
}

has_addons_k3s_installed() {
    $KUBECTL_PATH get crd | grep 'addons.k3s.cattle.io' >>$TEMP_DIR/mgmt_install.log 2>&1
}

has_pods_in_kube_system() {
    $KUBECTL_PATH get pods -n kube-system | grep 'Running' >>$TEMP_DIR/mgmt_install.log 2>&1
}

checked_install_k3s() {
    # Retry k3s install up to 5 times
    for g in {1..5}; do
        handleStep "retry #$g: Installing k3s..."
        install_k3s

        # Validate k3s installation (all of the checks are executed up to 5 times)
        handleInfo "Validating k3s installation..."
        sleep 10

        # Check that addons.k3s.cattle.io crd is installed
        handleCheck "Checking if addons.k3s.cattle.io CRD is installed..."
        hasAddons=false
        for ((i = 1; i <= RETRIES; i++)); do
            if has_addons_k3s_installed; then
                hasAddons=true
                break
            fi
            handleStep "addons.k3s.cattle.io CRD is not yet installed. Retrying in ${INTERVAL} seconds..."
            sleep ${INTERVAL}
        done

        if [ $hasAddons == false ]; then
            handleWarning "addons.k3s.cattle.io CRD is not installed. Retrying k3s installation..."
            uninstall_kubernetes
            sleep ${INTERVAL}
            continue
        fi

        handleSuccess "addons.k3s.cattle.io CRD is installed."

        # Check that kube-system namespace exists & has pods running
        handleCheck "Checking if kube-system namespace has pods running..."
        hasPods=false
        for ((i = 1; i <= RETRIES; i++)); do
            if has_pods_in_kube_system; then
                hasPods=true
                break
            fi
            handleStep "kube-system namespace does not have pods running. Retrying in ${INTERVAL} seconds..."
            sleep ${INTERVAL}
        done

        if [ $hasPods == false ]; then
            handleWarning "kube-system namespace does not have pods running. Retrying k3s installation..."
            uninstall_kubernetes
            sleep ${INTERVAL}
            continue
        fi

        handleSuccess "kube-system namespace has pods running."

        if [ $g -gt 1 ]; then
            logToSentry "k3s installation succeeded after multiple attempts." "warning"
        fi

        echo "Global retry #$g: k3s installation and validation succeeded."
        return
    done

    handleError "k3s installation failed after 5 retries."
}

# get_partition_sizes retrieves and displays information about disk partitions
# It checks the root partition (/) and home partition (/home) if it exists
# The function sets global variables:
# - root_total: Total size of root partition
# - root_available: Available space on root partition
# - home_total: Total size of home partition (if exists)
# - home_available: Available space on home partition (if exists)
# - has_home_partition: Boolean indicating if separate /home partition exists
get_partition_sizes() {
    handleStep "Checking partition sizes..."

    # Get root partition size and available space
    root_total=$(df -h / | awk 'NR==2 {print $2}')
    root_available=$(df -h / | awk 'NR==2 {print $4}')

    # Get home partition size and available space if it exists
    if mountpoint -q /home; then
        home_total=$(df -h /home | awk 'NR==2 {print $2}')
        home_available=$(df -h /home | awk 'NR==2 {print $4}')
        has_home_partition=true
    else
        has_home_partition=false
    fi

    # Display partition information
    handleInfo "Root partition (/):"
    handleInfo "  - Total size: $root_total"
    handleInfo "  - Available space: $root_available"

    if [[ $has_home_partition == true ]]; then
        handleInfo "Home partition (/home):"
        handleInfo "  - Total size: $home_total"
        handleInfo "  - Available space: $home_available"
    else
        handleInfo "No separate /home partition found"
    fi
}

# create_symlink_parent creates the parent directory for the symlink
# It ensures that /var/lib/rancher exists
create_symlink_parent() {
    handleStep "Creating parent directory for symlink..."
    if ! ls -l /var/lib/rancher && ! mkdir -p /var/lib/rancher; then
        handleError "Failed to create parent directory for symlink." "Check directory permissions."
        return 1
    fi
    handleSuccess "Parent directory for symlink created successfully"
    return 0
}

# backup_and_create_symlink creates a symlink from /var/lib/rancher/k3s to the target directory
# It also backs up the existing k3s directory if it exists
backup_and_create_symlink() {
    local target_dir="$1"
    handleStep "Creating symlink..."
    if [ -e "/var/lib/rancher/k3s" ]; then
        handleWarning "Existing k3s directory found. Creating backup..."
        if rm -rf /var/lib/rancher/k3s.backup && ! mv /var/lib/rancher/k3s /var/lib/rancher/k3s.backup; then
            handleError "Failed to backup existing rancher directory." "Check directory permissions."
            return 1
        fi
        handleSuccess "Existing k3s directory backed up successfully"
    fi

    if ! ln -s "$target_dir" /var/lib/rancher/k3s 2>/dev/null && [ ! -L /var/lib/rancher/k3s ]; then
        handleError "Failed to create symlink." "Check symlink permissions."
        return 1
    fi
    handleSuccess "Symlink created successfully"
    return 0
}

# setup_selinux_policies sets SELinux policies for the given directory
# It checks if SELinux is enabled and sets the appropriate policies
# If SELinux is disabled, it skips the policy setting
setup_selinux_policies() {
    local directory="$1"
    handleStep "Checking SELinux status..."
    if command -v getenforce > /dev/null 2>&1 && [[ "$(getenforce)" != "Disabled" ]] ; then
        handleInfo "SELinux is enabled. Setting SELinux policies for the folder..."
        if ! chcon -R system_u:object_r:var_lib_t:s0 "$directory"; then
            handleError "Failed to set SELinux policies for the folder." "Check SELinux configuration."
            return 1
        fi
        handleSuccess "SELinux policies for the folder set successfully"
    else
        handleInfo "SELinux is disabled. Skipping SELinux policies for the folder."
    fi
    return 0
}

# confirm_operation displays a confirmation prompt to the user
# It displays the provided description and waits for user input
# If the user confirms, it returns 0, otherwise it returns 1
confirm_operation() {
    local description="$1"
    handleInfo "$description"
    read -r -p "❓ Do you want to proceed with these changes? (Y/n): " confirm
    confirm=${confirm:-Y}
    if [[ ! $confirm =~ ^[Yy]$ ]]; then
        handleWarning "Operation cancelled. Returning to directory selection..."
        return 1
    fi
    return 0
}

# setup_fstab_mount adds the given mount path to /etc/fstab
# It ensures that the mount path is added to /etc/fstab if it is not already present
setup_fstab_mount() {
    local mount_path="$1"

    handleStep "Checking ${mount_path} mount..."
    if ! grep -q "${mount_path}" /etc/fstab; then
        handleStep "Adding ${mount_path} to /etc/fstab..."
        echo "${mount_path} ${mount_path} none bind 0 0" >> /etc/fstab
        if ! mount -a; then
            handleError "Failed to mount directory." "Check /etc/fstab configuration."
            return 1
        fi
        handleSuccess "Directory '$1' mounted successfully in /etc/fstab"
    fi
}

# setup_custom_k3s_directory sets up the custom k3s directory
# It performs the following steps:
# - Displays a confirmation prompt to the user
# - Creates a symlink from /var/lib/rancher/k3s to the target directory
# - Sets root as owner of the data directory
# - Ensures the directory is mounted in /etc/fstab
# - Ensures SELinux policies for the folder if necessary
setup_custom_k3s_directory() {
    local custom_directory="$1"
    local description="The following steps will be performed for custom directory:
1. Backup existing '/var/lib/rancher/k3s' to '/var/lib/rancher/k3s.backup'
2. Create symlink from '/var/lib/rancher/k3s' to '$custom_directory'
3. Set root as owner of the data directory '$custom_directory'
4. Ensure '$custom_directory' is mounted in /etc/fstab
5. Ensure SELinux policies for the folder if necessary"

    confirm_operation "$description" || return 1
    create_symlink_parent || return 1
    backup_and_create_symlink "$custom_directory" || return 1

    handleStep "Setting root as owner of the data directory '$custom_directory'"
    if ! chown -R root:root "$custom_directory"; then
        handleError "Failed to set owner." "Check directory permissions."
        return 1
    fi

    setup_selinux_policies "$custom_directory" || return 1
    setup_fstab_mount "$custom_directory" || return 1
    handleInfo "Successfully created symlink and set owner to '$custom_directory'"
    return 0
}

# setup_k3s_home_directory sets up the k3s home directory
# It performs the following steps:
# - Displays a confirmation prompt to the user
# - Creates a new system user 'k3s-data'
# - Creates directory '/home/k3s-data/rancher/k3s'
# - Creates symlink from '/var/lib/rancher/k3s' to '/home/k3s-data/rancher/k3s'
# - Sets root as owner of the k3s data directory
# - Ensures the directory is mounted in /etc/fstab
# - Ensures SELinux policies for the folder if necessary
setup_k3s_home_directory() {
    local k3s_home="/home/k3s-data/rancher/k3s"
    local description="The following steps will be performed for /home installation:
1. Create a new system user 'k3s-data'
2. Create directory '/home/k3s-data/rancher/k3s'
3. Create symlink from '/var/lib/rancher/k3s' to '/home/k3s-data/rancher/k3s'
4. Set root as owner of the k3s data directory
5. Ensure /home/k3s-data is mounted in /etc/fstab
6. Ensure SELinux policies for the folder if necessary"

    confirm_operation "$description" || return 1

    if ! id k3s-data > /dev/null 2>&1; then
        handleStep "Creating system user k3s-data..."
        if ! useradd -r -s /sbin/nologin k3s-data; then
            handleError "Failed to create system user k3s-data." "Check system user creation permissions."
            return 1
        fi
        handleSuccess "System user k3s-data created successfully"

        handleStep "Creating k3s data directory structure..."
        if ! mkdir -p "$k3s_home"; then
            handleError "Failed to create directory structure." "Check directory permissions."
            return 1
        fi
        handleSuccess "k3s data directory structure created successfully"
    else
        handleInfo "k3s-data user already exists. Skipping user creation..."
    fi

    create_symlink_parent || return 1
    backup_and_create_symlink "$k3s_home" || return 1

    handleStep "Setting directory ownership and permissions..."
    if ! chown -R root:root "$k3s_home" || ! chmod 700 "$k3s_home"; then
        handleError "Failed to set directory ownership and permissions." "Check permission settings."
        return 1
    fi
    handleSuccess "Directory ownership and permissions set successfully"

    setup_fstab_mount "$k3s_home" || return 1

    setup_selinux_policies "$k3s_home" || return 1
    handleSuccess "Successfully set up k3s home directory"
    return 0
}

# Helper function to backup existing k3s directory
backup_k3s_directory() {
    if [ -e "/var/lib/rancher/k3s" ]; then
        handleWarning "Existing k3s directory found. Creating backup..."
        if rm -rf /var/lib/rancher/k3s.backup && ! mv /var/lib/rancher/k3s /var/lib/rancher/k3s.backup; then
            handleError "Failed to backup existing rancher directory." "Check directory permissions."
            return 1
        fi
        handleSuccess "Existing k3s directory backed up successfully"
    fi
    return 0
}

# Helper function to set and validate K3S_DATA_DIR
set_k3s_data_dir() {
    local dir="$1"
    K3S_DATA_DIR="$dir"
    handleSuccess "K3s will be installed in: $K3S_DATA_DIR"
    export K3S_DATA_DIR
}

# Helper function to validate custom directory path
validate_custom_directory() {
    local path="$1"

    # Validate absolute path
    if [[ ! "$path" = /* ]]; then
        handleWarning "Please enter an absolute path (starting with /)."
        return 1
    fi

    # Create directory if it doesn't exist
    if ! mkdir -p "$path" 2>/dev/null; then
        handleWarning "Cannot create directory. Please check permissions and try again."
        return 1
    fi

    # Check if directory is writable
    if ! touch "$path/.test" 2>/dev/null; then
        handleWarning "Directory is not writable. Please check permissions and try again."
        return 1
    fi
    rm -f "$path/.test"

    return 0
}

# Helper function to manage k3s service
manage_k3s_service() {
    local action="$1"

    case "$action" in
        "stop")
            if systemctl is-active k3s > /dev/null 2>&1; then
                handleInfo "Found existing installation for K3s. Attempting to stop it while choosing the installation directory for K3s"
                if ! systemctl stop k3s; then
                    handleError "Failed to stop k3s." "Check k3s service status."
                    return 1
                fi
                handleSuccess "k3s stopped successfully"
            fi
            ;;
        "start")
            if ! systemctl is-active k3s > /dev/null 2>&1 && ! systemctl start k3s > /dev/null 2>&1; then
            	# This is an harmless warning case as K3s will be anyways installed later
                handleWarning "Failed to start k3s after choosing the installation directory."
            fi
            ;;
    esac
    return 0
}

# choose_k3s_location determines the location for K3s installation
# It handles pre-configured directory, autopilot mode, and user choice
choose_k3s_location() {

    # Handle autopilot mode
    if [[ $auto_select_k3s_installation_dir == "true" ]]; then
        backup_k3s_directory || return 1
        set_k3s_data_dir "/var/lib/rancher/k3s"
        handleInfo "Autopilot mode: defaulting K3s installation to root partition at $K3S_DATA_DIR"
        return
    fi

    # Check for existing k3s installation and skip K3s location selection
    if systemctl is-active k3s >/dev/null 2>&1; then
        handleInfo "Existing K3s installation detected."
        # Add these lines to show installation location
        if [ -d "/var/lib/rancher/k3s" ]; then
            if [ -L "/var/lib/rancher/k3s" ]; then
                actual_path=$(readlink -f "/var/lib/rancher/k3s")
                handleInfo "K3s is currently installed at: $actual_path"
            else
                handleInfo "K3s is currently installed at: /var/lib/rancher/k3s"
            fi
        else
            handleInfo "K3s installation location could not be determined"
        fi
        while true; do
            read -rp "❓ Would you like to skip K3s location selection and keep current installation? [Y/n] " skip_choice
            case $skip_choice in
                [Yy]* | "")
                    handleSuccess "Keeping existing K3s installation"
                    return 0
                    ;;
                [Nn]*)
                    handleInfo "Proceeding with K3s location selection"
                    break
                    ;;
                *)
                    handleWarning "Please answer Y or N"
                    ;;
            esac
        done
    fi

    # Handle pre-configured directory
    if [[ -n "$K3S_DATA_DIR" ]]; then
        handleInfo "Using pre-configured K3s data directory: $K3S_DATA_DIR"
        return
    fi


    # Handle silent mode
    if [[ "$SILENT" == "true" ]]; then
        set_k3s_data_dir "/var/lib/rancher/k3s"
        handleInfo "Silent mode: defaulting to root partition at $K3S_DATA_DIR"
        return
    fi

    # Stop k3s service if running
    manage_k3s_service "stop" || return 1

    # Calculate available space
    root_available_bytes=$(df / | awk 'NR==2 {print $4}')
    home_available_bytes=0
    if [[ $has_home_partition == true ]]; then
        home_available_bytes=$(df /home | awk 'NR==2 {print $4}')
    fi

    # Determine recommended option
    recommended_option="1"
    if [[ $has_home_partition == true && $home_available_bytes -gt $root_available_bytes ]]; then
        recommended_option="3"
    fi

    # Show options
    handleInfo "Please choose where to install K3s (💡 Option ${recommended_option} recommended for most space):"
    echo "1) Root partition (/var/lib/rancher/k3s) - ${root_available} available"
    echo "2) Custom directory (Expert mode)"
    [[ $has_home_partition == true ]] && echo "3) Home partition (/home/k3s-data/rancher/k3s) - ${home_available} available"

    # Handle user choice
    while true; do
        max_choice=$([[ $has_home_partition == true ]] && echo "3" || echo "2")
        choice=$(validate_numeric_input "Enter your choice (1-${max_choice}) [${recommended_option}]: " 1 "$max_choice" "$recommended_option" "$SILENT")

        case $choice in
            1)
                backup_k3s_directory || continue
                set_k3s_data_dir "/var/lib/rancher/k3s"
                break
                ;;
            2)
                while true; do
                    read -r -p "❓ Enter the full path for K3s installation: " custom_path
                    if validate_custom_directory "$custom_path" && setup_custom_k3s_directory "$custom_path"; then
                        set_k3s_data_dir  "$custom_path"
                        break
                    fi
                done
                break
                ;;
            3)
                if [[ $has_home_partition == true ]]; then
                    if setup_k3s_home_directory; then
                        set_k3s_data_dir "/home/k3s-data/rancher/k3s"
                        break
                    fi
                else
                    handleWarning "No separate home partition available. Please choose another option."
                fi
                ;;
        esac
    done

    # Start k3s service
    manage_k3s_service "start" || return 0
}

# Modify the install_kubernetes() function to include these new checks
install_kubernetes() {
    setup_tls_san
    perform_initial_checks

    # Add these lines after perform_initial_checks
    get_partition_sizes
    choose_k3s_location

    case $OS in
    "rhel")
        pre_install_rhel
        ;;
    "rocky")
        pre_install_rhel
        ;;
    # All other
    *)
        pre_install_generic
        ;;
    esac

    prepare_hostname

    prepare_kubelet_configuration
    prepare_nodename_configuration
    checked_install_k3s
    configure_dns
}

##########################################################################################
#                          UMH Installation                                    #
##########################################################################################

# Install UMH (if skip_umh_install is set)
install_umh() {
    function check_umh_installation {
        # Check if the united-manufacturing-hub namespace exists
        handleStep "Retrieving umh namespace"
        if $KUBECTL_PATH get namespace united-manufacturing-hub >>$TEMP_DIR/mgmt_install.log 2>&1; then
            handleWarning "UMH is already installed."

            # Ask the user if they want to overwrite the existing installation
            if [[ "$SILENT" == "true" ]]; then
                handleWarning "SILENT is set. Skipping confirmation..."
                # Remove namespace and all resources inside it
                if ! $KUBECTL_PATH delete namespace united-manufacturing-hub >>$TEMP_DIR/mgmt_install.log 2>&1; then
                    handleError "Failed to remove existing UMH installation" "Please delete the existing UMH installation manually, before running the script again."
                fi
            # If force_umh_overwrite then also skip confirmation
            elif [[ $force_umh_overwrite == true ]]; then
                handleWarning "FORCE_UMH_OVERWRITE is set. Skipping confirmation..."
                # Remove namespace and all resources inside it
                if ! $KUBECTL_PATH delete namespace united-manufacturing-hub >>$TEMP_DIR/mgmt_install.log 2>&1; then
                    handleError "Failed to remove existing UMH installation" "Please delete the existing UMH installation manually, before running the script again."
                fi
            else

                # if OS=flatcar, then show another warning, else show the normal warning
                if [[ "$OS" == "flatcar" ]]; then
                    handleWarning "UMH Helm Chart is already installed, which is normal when using your current OS (flatcar)"
                    handleWarning "You can safely overwrite the existing installation if you did not store any important data or configuration so far."
                    handleWarning "You can also skip the installation if you want to keep the existing installation. You will still be able to install the Management Companion."
                    read -r -p "❓ Do you want to overwrite? (y/N): " overwrite_umh
                    overwrite_umh=${overwrite_umh:-N}
                    if [[ ! $overwrite_umh =~ ^[Yy]$ ]]; then
                        handleWarning "Skipping UMH installation..." "You can run the script again to install UMH."
                        export install_umh=false # skip installation
                        return 0
                    fi
                else
                    handleWarning "UMH Helm Chart is already installed. This means you already installed the UMH Helm Chart in some form. If you don't have sensitive data in there, we recommend overwriting it to get the latest version. If you have sensitive data in there, we recommend that you abort the installation, and ask for help in our Discord"
                    handleWarning "ONLY CONTINUE IF YOU ARE 100% SURE"
                    read -r -p "❓ Do you want to overwrite the exiting UMH Helm Chart with the latest version and loose data stored in there? (y/N): " overwrite_umh
                    overwrite_umh=${overwrite_umh:-N}
                    if [[ ! $overwrite_umh =~ ^[Yy]$ ]]; then
                        handleWarning "Skipping UMH installation..." "You can run the script again to install UMH."
                        export install_umh=false # skip installation
                        return 0
                    fi
                fi

                # Remove namespace and all resources inside it
                handleStep "Remove old installation..."
                if ! $KUBECTL_PATH delete namespace united-manufacturing-hub >>$TEMP_DIR/mgmt_install.log 2>&1; then
                    handleError "Failed to remove existing UMH installation" "Please delete the existing UMH installation manually, before running the script again."
                fi
            fi
        else
            handleSuccess "UMH is not installed"
        fi
        # Check if current repo has same url as the new one.
        if $HELM_PATH repo list | grep -q "$UMH_HELM_CHART_URL"; then
            # Remove the existing Helm repo
            handleStep "Removing existing UMH Helm repo..."
            if ! $HELM_PATH repo remove united-manufacturing-hub >>$TEMP_DIR/mgmt_install.log 2>&1; then
                # Old repo name
                if ! $HELM_PATH repo remove umh >>$TEMP_DIR/mgmt_install.log 2>&1; then
                    handleWarning "Failed to remove existing UMH Helm repo." "Check the logs for any error messages."
                else
                    handleSuccess "Removed existing UMH Helm repo."
                fi
            fi
        fi

        # Check if the united-manufacturing-hub Helm repo exists
        if $HELM_PATH repo list | grep -q 'united-manufacturing-hub'; then
            handleSuccess "UMH Helm repo exists."
        else
            # Add the Helm repo as it does not exist
            handleStep "Adding UMH Helm repo..."
            if ! $HELM_PATH repo add united-manufacturing-hub "$UMH_HELM_CHART_URL" >>$TEMP_DIR/mgmt_install.log 2>&1; then
                handleError "Failed to add UMH Helm repo." "Check your network connection or try again later."
                return 1 # Return with error to skip the installation
            fi
            handleSuccess "UMH Helm repo added successfully."
        fi

        return 0 # Return successfully to continue with installation
    }

    handleCheck "Checking if UMH is already installed"

    export install_umh=true

    if ! check_umh_installation; then
        handleError "Failed to check UMH installation." "Check the logs for any error messages."

    fi

    if [[ $install_umh == true ]]; then
        # Install UMH
        # Create united-manufacturing-hub namespace
        handleStep "Creating UMH namespace"
        if ! $KUBECTL_PATH create namespace united-manufacturing-hub >>$TEMP_DIR/mgmt_install.log 2>&1; then
            handleError "Failed to create namespace united-manufacturing-hub." "Check the logs for any error messages."
        fi
        handleSuccess "Created UMH namespace"

        # Retry up to 5 times (network issues might affect this)
        hasUpdated=false
        for ((i = 1; i <= RETRIES; i++)); do
            # Update Helm repos
            handleStep "Updating Helm repos..."
            if ! $HELM_PATH repo update; then
                handleWarning "Failed to update Helm repos. Retrying in ${INTERVAL} seconds..."
                sleep ${INTERVAL}
            else
                hasUpdated=true
            fi
            if [[ $hasUpdated == true ]]; then
                handleSuccess "Updated Helm repos successfully."
                break
            fi
        done

        if [[ $hasUpdated == false ]]; then
            handleError "Failed to update Helm repos." "Check your network connection or try again later. If this issue persists, please contact support."
        fi

        # Install UMH
        handleStep "Installing UMH Helm Chart, this might take up to 15 minutes..."
        hasInstalled=false

        for ((i = 1; i <= RETRIES; i++)); do
            # Ignore SC2046 as the word splitting inside the subshell cannot occure
            # shellcheck disable=SC2046
            if ! $HELM_PATH --kubeconfig "$KUBECONFIG" install united-manufacturing-hub united-manufacturing-hub/united-manufacturing-hub --set serialNumber="$(hostname)" -n united-manufacturing-hub --debug --version "$UMH_VERSION" --timeout 10m $([ "$ALLOW_HELM_PRERELEASE" = true ] && echo "--devel") >>$TEMP_DIR/mgmt_install.log 2>&1; then
                handleWarning "Failed to install UMH Helm Chart. Retrying in ${INTERVAL} seconds..."
                # Let's put some additional info into the log
                ## Get the status of the Helm Chart
                if ! $HELM_PATH status united-manufacturing-hub >>$TEMP_DIR/mgmt_install.log 2>&1; then
                    handleWarning "Failed to get Helm status for UMH Helm Chart."
                fi
                ## Get the events of the Helm Chart
                if ! $KUBECTL_PATH get events -n united-manufacturing-hub >>$TEMP_DIR/mgmt_install.log 2>&1; then
                    handleWarning "Failed to get events for UMH Helm Chart."
                fi
                ## Get all available releases (helm repo list)
                if ! $HELM_PATH repo list >>$TEMP_DIR/mgmt_install.log 2>&1; then
                    handleWarning "Failed to get Helm repo list."
                fi
                ## Try to remove the faulty installation
                if ! $HELM_PATH --kubeconfig "$KUBECONFIG" uninstall united-manufacturing-hub -n united-manufacturing-hub >>$TEMP_DIR/mgmt_install.log 2>&1; then
                    handleWarning "Failed to uninstall faulty UMH Helm Chart."
                fi
                sleep ${INTERVAL}
            else
                hasInstalled=true
            fi
            if [[ $hasInstalled == true ]]; then
                break
            fi
        done

        if [[ $hasInstalled == false ]]; then
            handleError "Failed to install UMH Helm Chart." "Check the logs for any error messages or contact support."
        fi
    fi

    # Check if the namespace for companion exists
    handleStep "Checking if mgmtcompanion namespace exists..."
    if $KUBECTL_PATH get namespace mgmtcompanion >>$TEMP_DIR/mgmt_install.log 2>&1; then
        # This step might fail, due to race conditions, so we ignore the error
        # Example: The configmap is changed by the companion before the script can update it
        # Let's therefore re-try this up to 3 times
        for _ in {1..3}; do

            handleStep "Setting UMH configuration for mgmtcompanion..."
            # Fetch the current configuration of the config, update the umh field, and re-apply the updated configuration
            $KUBECTL_PATH get configmap mgmtcompanion-config -n mgmtcompanion -o json >"${TEMP_DIR}/configmap_temp.json"
            echo "Current UMH configuration for mgmtcompanion..." >>"$TEMP_DIR/mgmt_install.log"

            current_umh_merge_point="3"
            # Extract current umh_merge_point value (if exists)
            # Check if .umh_merge_point is set, if not, set it to 3
            if $JQ_PATH '.data.umh' "${TEMP_DIR}/configmap_temp.json" 2>/dev/null | $JQ_PATH '.umh_merge_point' 2>/dev/null | grep -q "null"; then
                handleInfo "umh_merge_point is set, extracting value"
                current_umh_merge_point=$($JQ_PATH '.data.umh' "${TEMP_DIR}/configmap_temp.json" | $JQ_PATH '.umh_merge_point')
                handleInfo "umh_merge_point: $current_umh_merge_point"
            else
                handleInfo "umh_merge_point is not set, setting it to 3"
                current_umh_merge_point="3"
            fi

            echo "Current UMH configuration for mgmtcompanion..." >>"$TEMP_DIR/mgmt_install.log"
            echo "umh_merge_point: $current_umh_merge_point" >>"$TEMP_DIR/mgmt_install.log"

            current_lastUpdated="0"
            # Extract current lastUpdated value (if exists)
            # Check if .lastUpdated is set, if not, set it to current unix timestamp
            if $JQ_PATH '.data.umh' "${TEMP_DIR}/configmap_temp.json" 2>/dev/null | $JQ_PATH '.lastUpdated' 2>/dev/null | grep -q "null"; then
                handleInfo "lastUpdated is set, extracting value"
                current_lastUpdated=$($JQ_PATH '.data.umh' "${TEMP_DIR}/configmap_temp.json" | $JQ_PATH '.lastUpdated')
                handleInfo "lastUpdated: $current_lastUpdated"
            else
                handleInfo "lastUpdated is not set, setting it to current unix timestamp"
                current_lastUpdated=$(date +%s)
            fi

            {
                echo "Current UMH configuration for mgmtcompanion..."
                echo "lastUpdated: $current_lastUpdated"
                cat "${TEMP_DIR}/configmap_temp.json"
            } >>"$TEMP_DIR/mgmt_install.log"

            actualString=""
            echo "IS_FULL_INSTALL: $IS_FULL_INSTALL" >>"$TEMP_DIR/mgmt_install.log"
            if [[ "$IS_FULL_INSTALL" == "true" ]]; then
                echo "Setting umh.enabled to true" >>"$TEMP_DIR/mgmt_install.log"
                actualString="true"
            else
                echo "Setting umh.enabled to false" >>"$TEMP_DIR/mgmt_install.log"
                actualString="false"
            fi
            {
                echo "actualString: $actualString"
                echo "current_umh_merge_point: $current_umh_merge_point"
                echo "current_lastUpdated: $current_lastUpdated"
            } >>"$TEMP_DIR/mgmt_install.log"

            releaseChannel="$RELEASE_CHANNEL"
            echo "RELEASE_CHANNEL: $releaseChannel" >>"$TEMP_DIR/mgmt_install.log"

            disableHardwareStatusCheck="$DISABLE_HARDWARE_STATUS_CHECK"
            if [[ "$disableHardwareStatusCheck" == "true" ]]; then
              handleWarning "Disabling hardware status check for mgmtcompanion, this should only be used for testing purposes."
            fi

            $JQ_PATH --arg is_full_install "$actualString" --arg ump "$current_umh_merge_point" --arg lU "$current_lastUpdated" --arg rC "$releaseChannel" --arg dHCSC "$disableHardwareStatusCheck" \
                '.data.umh = "enabled: \($is_full_install)\numh_merge_point: \($ump)\nlastUpdated: \($lU)\nreleaseChannel: \($rC)\ndisableHardwareStatusCheck: \($dHCSC)"' \
                "${TEMP_DIR}/configmap_temp.json" >"${TEMP_DIR}/modified_configmap_temp.json"

            # Add "helm" section in the configmap with Helm flags
            ## CHART_VERSION: chartVersion
            ## SAME_TOPIC_EXPERIENCE: sameTopicExperience
            $JQ_PATH --arg chartVersion "$UMH_VERSION" --arg sameTopicExperience "$SAME_TOPIC_EXPERIENCE" \
                '.data.helm = "chartVersion: \($chartVersion)\nsameTopicExperience: \($sameTopicExperience)"' "${TEMP_DIR}/modified_configmap_temp.json" >"${TEMP_DIR}/modified_configmap_temp2.json"

            {
                echo "Applying updated UMH configuration for mgmtcompanion..."
                cat "${TEMP_DIR}/modified_configmap_temp2.json"
            } >>"$TEMP_DIR/mgmt_install.log"

            $KUBECTL_PATH apply -f "${TEMP_DIR}/modified_configmap_temp2.json" >>"$TEMP_DIR/mgmt_install.log" 2>&1
            handleInfo "UMH configuration for mgmtcompanion updated successfully. (IS_FULL_INSTALL: $IS_FULL_INSTALL)"

            # Read back configmap to verify the changes
            if ! $KUBECTL_PATH get configmap mgmtcompanion-config -n mgmtcompanion -o json | $JQ_PATH '.data.umh' | grep -q "enabled: $IS_FULL_INSTALL"; then
                handleWarning "Failed to verify UMH configuration for mgmtcompanion." "Check the logs for any error messages."
            else
                handleSuccess "UMH configuration for mgmtcompanion verified successfully."
                break
            fi


        done

        # Set default Kafka broker for UMH
        $KUBECTL_PATH get configmap mgmtcompanion-config -n mgmtcompanion -o json >"${TEMP_DIR}/configmap_temp.json"
        $JQ_PATH '.data.brokers.kafka = "ip: \"united-manufacturing-hub-kafka.united-manufacturing-hub.svc.cluster.local\"\nport: 9092"' "${TEMP_DIR}/configmap_temp.json" >"${TEMP_DIR}/modified_configmap_temp.json"
        if ! $KUBECTL_PATH apply -f "${TEMP_DIR}/modified_configmap_temp.json" >>"$TEMP_DIR/mgmt_install.log" 2>&1; then
            handleWarning "Failed to set default Kafka broker for UMH." "Check the logs for any error messages."
        fi


        # Restart mgmtcompanion pod (if existing), to pick up the config changes
        $KUBECTL_PATH delete pod -n mgmtcompanion -l app=mgmtcompanion >>"$TEMP_DIR/mgmt_install.log" 2>&1

    fi
    handleSuccess "Installed UMH Helm Chart"
    return 0
}
##########################################################################################
#                          MgmtCompanion Installation                                    #
# This section of the script is dedicated to installing MgmtCompanion. It starts by     #
# checking for an existing MgmtCompanion installation. If found, the user is prompted   #
# to either overwrite the existing installation or abort the process. This decision can #
# be auto-confirmed in silent mode. The script then proceeds to install or overwrite    #
# MgmtCompanion, which includes creating necessary Kubernetes resources like namespaces,#
# configmaps, and statefulsets. It also sets up TLS verification and encodes the        #
# authentication token. Finally, the script waits for the MgmtCompanion pod to be ready #
# and verifies the installation's success.                                              #
##########################################################################################

install_mgmt() {

    # The install script shall check if the authentication token is present #574
    # Validate AUTH_TOKEN format
    handleCheck "Validating authentication token format..."
    if [[ -z "$AUTH_TOKEN" ]]; then
        handleError "Authentication token is not set." "Set the AUTH_TOKEN environment variable."
    elif [[ ! "$AUTH_TOKEN" =~ ^[a-fA-F0-9]{64}$ ]]; then
        handleError "Invalid authentication token format." "Ensure your authentication token is a 256-bit hex-encoded string."
    else
        handleSuccess "Authentication token format is valid."
    fi

    # The install script shall detect if MgmgCompanion is already installed #577
    handleCheck "Checking for existing MgmtCompanion installation..."
    if $KUBECTL_PATH get namespace mgmtcompanion >>$TEMP_DIR/mgmt_install.log 2>&1; then
        handleWarning "MgmtCompanion is already installed."

        # If the install script detects an existing MgmtCompanion installation it shall ask the user if he wants to overwrite or abort #578
        # Check if SILENT is set
        if [[ "$SILENT" == "true" ]]; then
            handleWarning "SILENT is set. Skipping confirmation..."
        else
            read -r -p "❓ Do you want to overwrite the existing installation? (y/N): " overwrite_confirm
            overwrite_confirm=${overwrite_confirm:-N}
            if [[ ! $overwrite_confirm =~ ^[Yy]$ ]]; then
                handleWarning "Skipping installation of compaion" "You can run the script again to install MgmtCompanion."
                return 1
            fi
        fi
        handleStep "Overwriting existing installation..."
        # Remove namespace and all resources inside it
        if $KUBECTL_PATH delete namespace mgmtcompanion >>"$TEMP_DIR"/mgmt_install.log 2>&1; then
            handleSuccess "Existing installation removed successfully."
        else
            handleError "Failed to remove existing installation." "Manually remove the existing installation using 'kubectl delete namespace mgmtcompanion' and run the script again."
        fi
    else
        handleSuccess "MgmtCompanion is not installed."
    fi

    # Install MgmtCompanion
    handleStep "Installing MgmtCompanion..."
    ## Create namespace
    if ! $KUBECTL_PATH create namespace mgmtcompanion >>$TEMP_DIR/mgmt_install.log 2>&1; then
        handleError "Failed to create namespace mgmtcompanion." "Check the logs above for any error messages."
    fi
    handleSuccess "Namespace mgmtcompanion created successfully."

    ## Download the MgmtCompanion manifests (configmap, secret, statefulset)
    handleStep "Downloading MgmtCompanion manifests..."
    if ! downloadFile "$CONFIGMAP_URL" "$TEMP_DIR/configmap.yaml"; then
        handleError "Failed to download configmap.yaml." "Check your network connection"
    fi

    handleSuccess "configmap.yaml downloaded successfully."
    if ! downloadFile "$SECRET_URL" "$TEMP_DIR/secret.yaml"; then
        handleError "Failed to download secret.yaml." "Check your network connection"
    fi

    handleSuccess "secret.yaml downloaded successfully."
    if ! downloadFile "$STATEFULSET_URL" "$TEMP_DIR/statefulset.yaml"; then
        handleError "Failed to download statefulset.yaml." "Check your network connection"
    fi

    handleSuccess "statefulset.yaml downloaded successfully."
    if ! downloadFile "$ROLE_URL" "$TEMP_DIR/role.yaml"; then
        handleError "Failed to download role.yaml." "Check your network connection"
    fi

    if ! downloadFile "$ROLE_BINDING_URL" "$TEMP_DIR/role_binding.yaml"; then
        handleError "Failed to download role_binding.yaml." "Check your network connection"
    fi

    if ! downloadFile "$PVC_URL" "$TEMP_DIR/pvc.yaml"; then
        handleError "Failed to download pvc.yaml." "Check your network connection"
    fi

    handleSuccess "MgmtCompanion manifests downloaded successfully."

    # Set __SHALL_SKIP_TLS_VERIFY__ based on INSECURE_TLS_SKIP_CERTIFICATE_CHECK inside the configmap.yaml
    handleStep "Setting data.tls.insecure-skip-tls-verify based $insecure_tls_skip_certificate_check..."
    if [[ $insecure_tls_skip_certificate_check == true ]]; then
        if ! $SED_PATH -i "s/__SHALL_SKIP_TLS_VERIFY__/true/g" $TEMP_DIR/configmap.yaml >>"$TEMP_DIR/mgmt_install.log" 2>&1; then
            handleError "Failed to set __SHALL_SKIP_TLS_VERIFY__ to true." "Check $TEMP_DIR/mgmt_install.log for more details."
        fi
    else
        if ! $SED_PATH -i "s/__SHALL_SKIP_TLS_VERIFY__/false/g" $TEMP_DIR/configmap.yaml >>"$TEMP_DIR/mgmt_install.log" 2>&1; then
            handleError "Failed to set __SHALL_SKIP_TLS_VERIFY__ to false." "Check $TEMP_DIR/mgmt_install.log for more details."
        fi
    fi

    # Set __SHALL_SKIP_TLS_VERIFY__ based on MGMT_CONFIG_DEBUG_DISABLE_BACKEND_CONNECTION inside the configmap.yaml
    handleStep "Setting data.debug.disableBackendConnection based $MGMT_CONFIG_DEBUG_DISABLE_BACKEND_CONNECTION..."
    if [[ $MGMT_CONFIG_DEBUG_DISABLE_BACKEND_CONNECTION == true ]]; then
        if ! $SED_PATH -i "s/__SHALL_DISABLE_BACKEND_CONNECTION__/true/g" $TEMP_DIR/configmap.yaml >>"$TEMP_DIR/mgmt_install.log" 2>&1; then
            handleError "Failed to set __SHALL_DISABLE_BACKEND_CONNECTION__ to true." "Check $TEMP_DIR/mgmt_install.log for more details."
        fi
    else
        if ! $SED_PATH -i "s/__SHALL_DISABLE_BACKEND_CONNECTION__/false/g" $TEMP_DIR/configmap.yaml >>"$TEMP_DIR/mgmt_install.log" 2>&1; then
            handleError "Failed to set __SHALL_DISABLE_BACKEND_CONNECTION__ to false." "Check $TEMP_DIR/mgmt_install.log for more details."
        fi
    fi

    # Encode the AUTH_TOKEN to base64 as Kubernetes secrets require base64 encoded values
    handleStep "Encoding the authentication token..."
    encoded_auth_token=$(echo -n "$AUTH_TOKEN" | $BASE64_PATH)
    ## Apply the MgmtCompanion manifests
    handleStep "Applying MgmtCompanion manifests..."
    if ! $KUBECTL_PATH apply -f $TEMP_DIR/configmap.yaml -n mgmtcompanion; then
        handleError "Failed to apply configmap.yaml." "Check the logs above for any error messages."

    fi
    handleSuccess "configmap.yaml applied successfully."
    if ! $KUBECTL_PATH apply -f $TEMP_DIR/secret.yaml -n mgmtcompanion; then
        handleError "Failed to apply secret.yaml." "Check the logs above for any error messages."

    fi
    # Fetch the current configuration of the secret, update the auth-token field, and re-apply the updated configuration
    if ! $KUBECTL_PATH get secret mgmtcompanion-secret -n mgmtcompanion -o json |
        $JQ_PATH --arg token "$encoded_auth_token" '.data["auth-token"]=$token' |
        $KUBECTL_PATH apply -f -; then
        handleError "Failed to update auth-token in mgmtcompanion-secret." "Check the logs above for any error messages."

    fi
    handleStep "validating secret"

    # Fetch the current configuration of the config, update the location_enterprise field, and re-apply the updated configuration
    $KUBECTL_PATH get configmap mgmtcompanion-config -n mgmtcompanion -o json >"${TEMP_DIR}/configmap_temp.json" 2>>"$TEMP_DIR/mgmt_install.log"
    $JQ_PATH --arg location_enterprise "$LOCATION_ENTERPRISE" \
        --arg location_site "$LOCATION_SITE" \
        --arg location_area "$LOCATION_AREA" \
        --arg location_line "$LOCATION_LINE" \
        --arg location_workcell "$LOCATION_WORKCELL" \
        '.data.location = "enterprise: " + $location_enterprise + "\nsite: " + $location_site + "\narea: " + $location_area + "\nline: " + $location_line + "\nworkcell: " + $location_workcell' \
        "${TEMP_DIR}/configmap_temp.json" >"${TEMP_DIR}/modified_configmap_temp.json" 2>>"$TEMP_DIR/mgmt_install.log"

    $KUBECTL_PATH apply -f "${TEMP_DIR}/modified_configmap_temp.json" >>"$TEMP_DIR/mgmt_install.log" 2>&1

    # Fetch the current configuration of the config, update the umh field, and re-apply the updated configuration
    $KUBECTL_PATH get configmap mgmtcompanion-config -n mgmtcompanion -o json >"${TEMP_DIR}/configmap_temp.json"

    current_umh_merge_point="3"
    # Extract current umh_merge_point value (if exists)
    # Check if .umh_merge_point is set, if not, set it to 3
    if $JQ_PATH '.data.umh' "${TEMP_DIR}/configmap_temp.json" 2>/dev/null | $JQ_PATH '.umh_merge_point' 2>/dev/null | grep -q "null"; then
        handleInfo "umh_merge_point is set, extracting value"
        current_umh_merge_point=$($JQ_PATH '.data.umh' "${TEMP_DIR}/configmap_temp.json" | $JQ_PATH '.umh_merge_point')
        handleInfo "umh_merge_point: $current_umh_merge_point"
    else
        handleInfo "umh_merge_point is not set, setting it to 3"
        current_umh_merge_point="3"
    fi

    echo "Current UMH configuration for mgmtcompanion..." >>"$TEMP_DIR/mgmt_install.log"
    echo "umh_merge_point: $current_umh_merge_point" >>"$TEMP_DIR/mgmt_install.log"

    current_lastUpdated="0"
    # Extract current lastUpdated value (if exists)
    # Check if .lastUpdated is set, if not, set it to current unix timestamp
    if $JQ_PATH '.data.umh' "${TEMP_DIR}/configmap_temp.json" 2>/dev/null | $JQ_PATH '.lastUpdated' 2>/dev/null | grep -q "null"; then
        handleInfo "lastUpdated is set, extracting value"
        current_lastUpdated=$($JQ_PATH '.data.umh' "${TEMP_DIR}/configmap_temp.json" | $JQ_PATH '.lastUpdated')
        handleInfo "lastUpdated: $current_lastUpdated"
    else
        handleInfo "lastUpdated is not set, setting it to current unix timestamp"
        current_lastUpdated=$(date +%s)
    fi

    actualString=""
    echo "IS_FULL_INSTALL: $IS_FULL_INSTALL" >>"$TEMP_DIR/mgmt_install.log"
    if [[ "$IS_FULL_INSTALL" == "true" ]]; then
        echo "Setting umh.enabled to true" >>"$TEMP_DIR/mgmt_install.log"
        actualString="true"
    else
        echo "Setting umh.enabled to false" >>"$TEMP_DIR/mgmt_install.log"
        actualString="false"
    fi
    {
        echo "actualString: $actualString"
        echo "current_umh_merge_point: $current_umh_merge_point"
        echo "current_lastUpdated: $current_lastUpdated"
    } >>"$TEMP_DIR/mgmt_install.log"

    echo "Setting umh.enabled to $actualString" >>"$TEMP_DIR/mgmt_install.log"
    releaseChannel="$RELEASE_CHANNEL"
    echo "RELEASE_CHANNEL: $releaseChannel" >>"$TEMP_DIR/mgmt_install.log"

    disableHardwareStatusCheck="$DISABLE_HARDWARE_STATUS_CHECK"
    if [[ "$disableHardwareStatusCheck" == "true" ]]; then
      handleWarning "Disabling hardware status check for mgmtcompanion, this should only be used for testing purposes."
    fi

    $JQ_PATH --arg is_full_install "$actualString" --arg ump "$current_umh_merge_point" --arg lU "$current_lastUpdated" --arg rC "$releaseChannel" --arg dHCSC "$disableHardwareStatusCheck" \
        '.data.umh = "enabled: \($is_full_install)\numh_merge_point: \($ump)\nlastUpdated: \($lU)\nreleaseChannel: \($rC)\ndisableHardwareStatusCheck: \($dHCSC)"' \
        "${TEMP_DIR}/configmap_temp.json" >"${TEMP_DIR}/modified_configmap_temp.json"

    # Add "helm" section in the configmap with Helm flags
    ## CHART_VERSION: chartVersion
    ## SAME_TOPIC_EXPERIENCE: sameTopicExperience
    $JQ_PATH --arg chartVersion "$UMH_VERSION" --arg sameTopicExperience "$SAME_TOPIC_EXPERIENCE" \
        '.data.helm = "chartVersion: \($chartVersion)\nsameTopicExperience: \($sameTopicExperience)"' "${TEMP_DIR}/modified_configmap_temp.json" >"${TEMP_DIR}/modified_configmap_temp2.json"

    $KUBECTL_PATH apply -f "${TEMP_DIR}/modified_configmap_temp2.json" >>"$TEMP_DIR/mgmt_install.log" 2>&1

    # Verify the auth-token field in the secret
    auth_token_value=$($KUBECTL_PATH get secret mgmtcompanion-secret -n mgmtcompanion -o jsonpath='{.data.auth-token}' | base64 -d)

    if [[ "$auth_token_value" != "null" && -n "$auth_token_value" ]]; then
        handleSuccess "auth-token is set successfully in mgmtcompanion-secret."
    else
        handleError "auth-token is not set or is null in mgmtcompanion-secret." "Please check the secret configuration and try again."

    fi
    handleSuccess "secret.yaml applied successfully."
    # Use$SED_PATH to replace the image version in statefulset.yaml (placeholder is __VERSION__)
    if ! $SED_PATH -i "s/__VERSION__/$IMAGE_VERSION/g" $TEMP_DIR/statefulset.yaml >>"$TEMP_DIR/mgmt_install.log" 2>&1; then
        handleError "Failed to update image version in statefulset.yaml." "Check $TEMP_DIR/mgmt_install.log for more details."
    fi
    # Use$SED_PATH to replace the API_URL in statefulset.yaml (placeholder is __API_URL__)
    if ! $SED_PATH -i "s|__API_URL__|$API_URL|g" $TEMP_DIR/statefulset.yaml >>"$TEMP_DIR/mgmt_install.log" 2>&1; then
        handleError "Failed to update API_URL in statefulset.yaml." "Check $TEMP_DIR/mgmt_install.log for more details."
    fi

    handleSuccess "Image version updated in statefulset.yaml successfully."
    if ! $KUBECTL_PATH apply -f $TEMP_DIR/statefulset.yaml -n mgmtcompanion; then
        handleError "Failed to apply statefulset.yaml." "Check the logs above for any error messages."
    fi

    handleSuccess "statefulset.yaml applied successfully."
    if ! $KUBECTL_PATH apply -f $TEMP_DIR/role.yaml -n mgmtcompanion; then
        handleError "Failed to apply role.yaml." "Check the logs above for any error messages."
    fi

    handleSuccess "role.yaml applied successfully."
    if ! $KUBECTL_PATH apply -f $TEMP_DIR/role_binding.yaml -n mgmtcompanion; then
        handleError "Failed to apply role_binding.yaml." "Check the logs above for any error messages."
    fi
    handleSuccess "role_binding.yaml applied successfully."

    if ! $KUBECTL_PATH apply -f $TEMP_DIR/pvc.yaml -n mgmtcompanion; then
        handleError "Failed to apply pvc.yaml." "Check the logs above for any error messages."
    fi
    handleSuccess "pvc.yaml applied successfully."

    handleSuccess "MgmtCompanion manifests applied successfully."

    handleStep "Patch config map to add host infrastructure and network configs"
    cat <<EOF >"${TEMP_DIR}/patch.yaml"
data:
  os: |
    architecture: "$OS_ARCH"
  network: |
    externalIP: "$EXTERNAL_IP"
    externalGateway: "$EXTERNAL_IP_GATEWAY"
    externalDeviceInterface: "$EXTERNAL_IP_INTERFACE"
    dnsServer: "$DNS_SERVER"
  k3s: |
    dataDir: "$K3S_DATA_DIR"
    diskSpaceCheck: "$IGNORE_DISK_SPACE_ERROR"
EOF

    if $KUBECTL_PATH get configmap mgmtcompanion-config -n mgmtcompanion >/dev/null 2>&1; then
        if ! $KUBECTL_PATH patch configmap mgmtcompanion-config -n mgmtcompanion --type=merge --patch-file "${TEMP_DIR}/patch.yaml"; then
            handleError "Failed to patch configmap companionmgmt-config." "Check the logs above for any error messages."
        fi
        handleSuccess "configmap mgmtcompanion-config patched successfully."
    else
        handleWarning "Configmap mgmtcompanion-config does not exist." "Cannot apply patch for infrastructue and network configs"
    fi

    ## Wait a few seconds for the pod to start
    handleSleep "Waiting for kubernetes to finalize the installation..." 5

    # Define a function to check pod readiness
    function check_pod_readiness {
        local pod_name=$1
        local namespace=$2
        $KUBECTL_PATH get pod "$pod_name" -n "$namespace" -o jsonpath='{.status.conditions[?(@.type=="Ready")].status}' 2>/dev/null | grep -q "True"
    }

    # Check for successful installation by querying k3s to check if the following is true (all resources are inside the mgmtcompanion namespace)
    # - statefulset: mgmtcompanion
    # - secret: mgmtcompanion-secret
    # - configmap: mgmtcompanion-config
    if [[ $($KUBECTL_PATH get statefulsets -n mgmtcompanion --field-selector metadata.name=mgmtcompanion -o jsonpath='{.items[*].metadata.name}') == "mgmtcompanion" ]] &&
        [[ $($KUBECTL_PATH get secrets -n mgmtcompanion --field-selector metadata.name=mgmtcompanion-secret -o jsonpath='{.items[*].metadata.name}') == "mgmtcompanion-secret" ]] &&
        [[ $($KUBECTL_PATH get configmaps -n mgmtcompanion --field-selector metadata.name=mgmtcompanion-config -o jsonpath='{.items[*].metadata.name}') == "mgmtcompanion-config" ]]; then
        mgmtcompanion_pod=$($KUBECTL_PATH get pods -n mgmtcompanion --selector=statefulset.kubernetes.io/pod-name=mgmtcompanion-0 -o jsonpath='{.items[*].metadata.name}')
        ELAPSED=0
        handleSleep "Waiting for MgmtCompanion pod ($mgmtcompanion_pod) to be running and ready..." 5
        while ! check_pod_readiness "$mgmtcompanion_pod" mgmtcompanion && [ $ELAPSED -lt "$TIMEOUT" ]; do
            handleSleep "Waiting for MgmtCompanion ($mgmtcompanion_pod) pod to be ready..." "$INTERVAL"
            mgmtcompanion_pod=$($KUBECTL_PATH get pods -n mgmtcompanion --selector=statefulset.kubernetes.io/pod-name=mgmtcompanion-0 -o jsonpath='{.items[*].metadata.name}')
            ELAPSED=$((ELAPSED + INTERVAL))
        done

        # If pod is not ready within 2 minute, show the container logs
        if ! check_pod_readiness "$mgmtcompanion_pod" mgmtcompanion; then
            handleWarning "MgmtCompanion pod is not ready within 2 minutes. Displaying container logs..."
            $KUBECTL_PATH logs "$mgmtcompanion_pod" -n mgmtcompanion --all-containers >"$TEMP_DIR/failure_pod.log"
            echo "==== POD LOGS ===="
            cat "$TEMP_DIR/failure_pod.log"
            echo "==== END OF POD LOGS ===="

            $KUBECTL_PATH get configmap mgmtcompanion-config -n mgmtcompanion -o yaml >"$TEMP_DIR/failure_configmap.yaml"
            echo "==== CONFIGMAP ===="
            cat "$TEMP_DIR/failure_configmap.yaml"
            echo "==== END OF CONFIGMAP ===="

            $KUBECTL_PATH get secret mgmtcompanion-secret -n mgmtcompanion -o yaml >"$TEMP_DIR/failure_secret.yaml"
            echo "==== SECRET ===="
            cat "$TEMP_DIR/failure_secret.yaml"
            echo "==== END OF SECRET ===="

            $KUBECTL_PATH describe statefulset mgmtcompanion -n mgmtcompanion >"$TEMP_DIR/failure_statefulset.log"
            echo "==== STATEFULSET LOGS ===="
            cat "$TEMP_DIR/failure_statefulset.log"
            echo "==== END OF STATEFULSET LOGS ===="
            exit 1
        fi

        handleSuccess "Installation successful."
        return 0
    else
        handleError "Installation failed - Required resources are missing in the mgmtcompanion namespace." "Verify the installation steps and ensure all necessary resources are created."

    fi
}
# Helper function to configure a sysctl setting
configure_sysctl_setting() {
  local setting_name="$1"
  local required_min="$2"

  handleStep "Checking if $setting_name is set to at least $required_min..."

  # Retrieve the current value of the sysctl setting
  local current_value
  current_value=$(sysctl -n "$setting_name" 2>/dev/null)

  # Check if the current value meets the requirement
  if [[ -n "$current_value" && "$current_value" -ge "$required_min" ]]; then
    handleSuccess "$setting_name is already set to $current_value."
  else
    handleInfo "Setting $setting_name from $current_value to $required_min..."

    # Attempt to set the sysctl parameter
    if ! sysctl -w "${setting_name}=${required_min}" >>"$TEMP_DIR/mgmt_install.log" 2>&1; then
      handleError "Failed to set $setting_name to $required_min." "Check the logs in $TEMP_DIR/mgmt_install.log for details."
      return 1
    fi
    # Check if /etc/sysctl.d directory exists
    if [ -d /etc/sysctl.d ]; then
      handleInfo "Persisting $setting_name to /etc/sysctl.d..."

      # Backup the full folder
      timestamp=$(date +%s)
      if ! cp -r /etc/sysctl.d "/etc/sysctl.d-${timestamp}.bak" >>"$TEMP_DIR/mgmt_install.log" 2>&1; then
        handleError "Failed to backup /etc/sysctl.d." "Check the logs in $TEMP_DIR/mgmt_install.log for details."
        return 1
      fi

      handleInfo "Backed up /etc/sysctl.d to /etc/sysctl.d-${timestamp}.bak."

      # Persist the setting in /etc/sysctl.d
      if ! echo "${setting_name}=${required_min}" >/etc/sysctl.d/99-mgmtcompanion.conf; then
        handleError "Failed to persist $setting_name=${required_min} to /etc/sysctl.d/99-mgmtcompanion.conf." "Check the logs in $TEMP_DIR/mgmt_install.log for details."
        return 1
      fi
    elif [ -f /etc/sysctl.conf ]; then
      handleInfo "Persisting $setting_name to /etc/sysctl.conf..."

      # Backup the current /etc/sysctl.conf
      timestamp=$(date +%s)
      if ! cp -f /etc/sysctl.conf "/etc/sysctl.conf-${timestamp}.bak" >>"$TEMP_DIR/mgmt_install.log" 2>&1; then
        handleError "Failed to backup /etc/sysctl.conf." "Check the logs in $TEMP_DIR/mgmt_install.log for details."
        return 1
      fi
      handleInfo "Backed up /etc/sysctl.conf to /etc/sysctl.conf-${timestamp}.bak."

      # Persist the setting in /etc/sysctl.conf
      if grep -q "^${setting_name}=" /etc/sysctl.conf; then
        # Update existing entry
        if ! sed -i "s/^${setting_name}=.*/${setting_name}=${required_min}/" /etc/sysctl.conf; then
          handleError "Failed to update $setting_name in /etc/sysctl.conf." "Check the logs in $TEMP_DIR/mgmt_install.log for details."
          return 1
        fi
      else
        # Add new entry
        if ! echo "${setting_name}=${required_min}" >>/etc/sysctl.conf; then
          handleError "Failed to persist $setting_name=${required_min} to /etc/sysctl.conf." "Check the logs in $TEMP_DIR/mgmt_install.log for details."
          return 1
        fi
      fi
    else
      handleWarning "Neither /etc/sysctl.d nor /etc/sysctl.conf exists." "Cannot persist $setting_name. Ensure that /etc/sysctl.d directory or /etc/sysctl.conf file is present."
      return 1
    fi

    handleSuccess "$setting_name set to $required_min."
  fi
}

# Main function to patch sysctl settings
patch_sysctl() {
  handleStep "Starting sysctl configuration for cAdvisor requirements..."

  # Configure fs.inotify.max_user_watches
  configure_sysctl_setting "fs.inotify.max_user_watches" 524288 || return 1

  # Configure fs.inotify.max_user_instances
  configure_sysctl_setting "fs.inotify.max_user_instances" 8192 || return 1

  # Reload the sysctl settings to apply changes
  handleStep "Reloading sysctl settings..."
  if ! sysctl --system >>"$TEMP_DIR/mgmt_install.log" 2>&1; then
    handleError "Failed to reload sysctl settings." "Check the logs in $TEMP_DIR/mgmt_install.log for details."
    return 1
  fi

  handleSuccess "Sysctl settings reloaded successfully."
}

###############################
# UNINSTALL PART #######
#######################

remove_namespace_and_pv() {
    # Define KUBECTL_PATH if unset (using which kubectl)
    KUBECTL_PATH=$(which kubectl)

    local namespace="$1"

    if $KUBECTL_PATH get namespace "$namespace" >>$TEMP_DIR/mgmt_install.log 2>&1; then
        local refPVs
        local pv_name

        # Retrieve PV names
        refPVs=$($KUBECTL_PATH get pv -o json | jq -r --arg ns "$namespace" '.items[] | select(.spec.claimRef.namespace == $ns) | .metadata.name')

        # Conditionally delete namespace (only if it exists)
        retries=3
        handleStep "Deleting namespace $namespace..."
        for ((i = 1; i <= retries; i++)); do
            if $KUBECTL_PATH delete namespace "$namespace" --grace-period=1 --ignore-not-found=true --timeout=30s >>$TEMP_DIR/mgmt_install.log 2>&1; then
                handleSuccess "Deleted namespace $namespace."
                break
            else
                handleWarning "Failed to delete namespace $namespace." "Retrying in 10 seconds..."
                sleep 10
            fi
        done

        # Attempt to cleanup PVs
        handleStep "Cleaning up Persistent Volumes..."
        for pv_name in $refPVs; do
            $KUBECTL_PATH delete pv "$pv_name" || true
            handleInfo "Deleted PV $pv_name."
        done
    else
        handleInfo "Namespace $namespace does not exist."
    fi
}

uninstall_mgmt() {
    remove_namespace_and_pv "mgmtcompanion"
}

uninstall_umh() {
    remove_namespace_and_pv "united-manufacturing-hub"
}

uninstall_kubernetes() {
    # Check the operating system
    if [ "$OS" = "flatcar" ]; then
        # Execute uninstall script for Flatcar
        handleInfo "Executing Flatcar-specific uninstall script"
        # Validate that /usr/local/bin/k3s-uninstall.sh exists
        if [ -f /opt/bin/k3s-uninstall.sh ]; then
            if ! /opt/bin/k3s-uninstall.sh >>"$TEMP_DIR/mgmt_install.log" 2>&1; then
                handleError "Failed to execute k3s-uninstall.sh." "Check the logs above for any error messages."
            fi
        else
            handleWarning "k3s-uninstall.sh not found." "Ensure that k3s is installed and the uninstall script is available."
        fi
    else
        # Execute uninstall script for RHEL and generic systems
        handleInfo "Executing RHEL/generic uninstall script"
        # Validate that /usr/local/bin/k3s-uninstall.sh exists
        if [ -f /usr/local/bin/k3s-uninstall.sh ]; then
            if ! /usr/local/bin/k3s-uninstall.sh >>"$TEMP_DIR/mgmt_install.log" 2>&1; then
                handleError "Failed to execute k3s-uninstall.sh." "Check the logs above for any error messages."
            fi
        else
            handleWarning "k3s-uninstall.sh not found." "Ensure that k3s is installed and the uninstall script is available."
        fi
    fi
    handleSuccess "Kubernetes uninstalled successfully."
}

uninstall_tools() {
    uninstall_helm
    uninstall_kubectl
}

uninstall_tools_rhel() {

    # Uninstall SELinux packages
    handleStep "Uninstalling SELinux packages"
    yum remove -y container-selinux selinux-policy-base >>"$TEMP_DIR/mgmt_install.log" 2>&1 || true

    handleStep "Removing k3s SELinux policy"
    yum remove -y "${CUSTOM_MGMT_URL}/binaries/k3s/${INSTALL_K3S_SELINUX_VERSION}" >>"$TEMP_DIR/mgmt_install.log" 2>&1 || true

    # Remove SELinux modules
    handleStep "Removing k3s SELinux modules"
    semodule -r k3s >>"$TEMP_DIR/mgmt_install.log" 2>&1 || true

    # Remove dangling semodules
    handleStep "Removing dangling semodules"
    declare modules_to_delete
    if ! modules_to_delete=$(semodule --list=full | grep k3s | awk '{print $1}') >>"$TEMP_DIR/mgmt_install.log" 2>&1; then
        handleWarning "Failed to list dangling semodules." "Check the logs above for any error messages."
    else
        handleInfo "Removing the following modules: $modules_to_delete"
        if [ -n "$modules_to_delete" ]; then
            semodule -X "$modules_to_delete" -r k3s >>"$TEMP_DIR/mgmt_install.log" 2>&1 || true
        else
            handleInfo "Nothing to delete."
        fi
    fi

}

uninstall_cleanup() {
    handleStep "Cleaning up..."

    # Remove previously downloaded content
    rm "${TEMP_DIR}/install.sh" >>"$TEMP_DIR/mgmt_install.log" 2>&1 || true
    rm "${TEMP_DIR}/"* >>"$TEMP_DIR/mgmt_install.log" 2>&1 || true

    # If on flatcar, also delete the /opt/DO_NOT_DELETE_UMH_IS_INSTALLED file
    if [ "$OS" = "flatcar" ]; then
        rm /opt/DO_NOT_DELETE_UMH_IS_INSTALLED >>"$TEMP_DIR/mgmt_install.log" 2>&1 || true
    fi
}

# Function to handle the uninstallation process
uninstall_all() {
    handleStep "Installing kubectl (if not already installed)"
    install_kubectl
    handleSuccess "kubectl installed!"

    handleStep "Removing the United Manufacturing Hub..."
    uninstall_umh
    handleSuccess "UMH successfully removed!"

    handleStep "Removing Management Companion..."
    uninstall_mgmt
    handleSuccess "Management Companion successfully removed!"

    handleStep "Removing kubernetes..."
    uninstall_kubernetes
    handleSuccess "Kubernetes successfully removed!"

    uninstall_tools

    handleStep "Uninstalling RHEL specific tools.."
    uninstall_tools_rhel
    handleSuccess "Uninstalled RHEL specific tools"

    handleStep "Additional Cleanup"
    uninstall_cleanup
    handleSuccess "Cleanup finished!"
}

install_all() {
    handleStep "Installing kubectl..."
    install_kubectl
    handleInstalled "kubectl installed!"

    handleStep "Installing Helm..."
    install_helm
    handleInstalled "kubectl installed!"

    handleStep "Installing Kubernetes..."
    install_kubernetes
    handleInstalled "Kubernetes installed!"

    if [[ "$skip_umh_install" == "false" ]]; then
        handleStep "Installing UMH..."
        if install_umh; then
            handleInstalled "UMH installed successfully!"
        else
            handleWarning "UMH not installed"
        fi
    else
        handleWarning "Skipping UMH installation", "Set UMH_SKIP_INSTALL to false if this is incorrect"
    fi

    if [[ "$skip_companion_install" == "false" ]]; then
        handleStep "Installing Management Companion..."
        if install_mgmt; then
            handleInstalled "Management Companion installed successfully!"
        else
            handleWarning "Management Companion not installed"
        fi
    else
        handleWarning "Skipping Management Companion installation", "Set MGMT_SKIP_INSTALL to false if this is incorrect"
    fi

    # Restart the mgmtcompanion here, to ensure config changes are re-read (if it exists)
    ## Check if companion pod exists
    if $KUBECTL_PATH get pods -n mgmtcompanion --selector=statefulset.kubernetes.io/pod-name=mgmtcompanion-0 -o jsonpath='{.items[*].metadata.name}' >/dev/null 2>&1; then
        handleStep "Restarting mgmtcompanion pod..."
        $KUBECTL_PATH delete pod -n mgmtcompanion -l app=mgmtcompanion >>"$TEMP_DIR/mgmt_install.log" 2>&1
        handleSuccess "mgmtcompanion pod restarted successfully."
    fi

}

# Set OS is relevant for all
recreate_temporary_directory
check_root_user
set_OS_info
patch_rocky
verify_and_set_tool_paths
verify_system
adjust_interval_based_on_speedtest

# Do the following step only during the INSTALL process
if [[ "$UNINSTALL" == "false" ]]; then
    patch_sysctl
    ask_external_ip
    validate_external_ip
fi

# Add /usr/local/bin to PATH
export PATH=$PATH:/usr/local/bin

# Main execution logic
if [[ "$INSTALL_HELM" == "true" ]]; then
    handleStep "Installing Helm..."
    install_helm
    handleSuccess "Helm installed!"
elif [[ "$UNINSTALL_HELM" == "true" ]]; then
    handleStep "Removing Helm..."
    uninstall_helm
    handleSuccess "Helm removed!"
elif [[ "$INSTALL_KUBECTL" == "true" ]]; then
    handleStep "Installing kubectl..."
    install_kubectl
elif [[ "$UNINSTALL_KUBECTL" == "true" ]]; then
    handleStep "Removing kubectl..."
    uninstall_kubectl
    handleSuccess "kubectl removed!"
elif [[ "$INSTALL_KUBERNETES" == "true" ]]; then
    handleStep "Installing kubernetes..."
    install_kubernetes
    handleSuccess "Kubernetes installed!"
elif [[ "$UNINSTALL_KUBERNETES" == "true" ]]; then
    handleStep "Removing kubernetes..."
    uninstall_kubernetes
    handleSuccess "Kubernetes removed!"
elif [[ "$UNINSTALL" == "true" ]]; then
    handleStep "Removing the United Manufacturing Hub..."
    uninstall_all
    handleInstalled "Removal complete! Thank you for using the United Manufacturing Hub."
else
    handleStep "Initiating installation process..."
    install_all
    handleInstalled "Installation complete!"
fi
