#!/usr/bin/env bash

AUTH_CONF_PATH="/etc/yum/vars/elstoken"
# The installer package is noarch: the same RPM serves every architecture.
PACKAGE_URI="https://repo.tuxcare.com/centos7-els/els-os-release-install.el7.noarch.rpm"
# Architectures the centos7-els repository is published for. Checked before
# installing so an unsupported host fails with a clear message instead of an
# empty, unusable repository afterwards.
SUPPORTED_ARCHES="x86_64 aarch64 i686"

show_usage() {
    echo 'Usage: install-centos7-els-repo-ip.sh [OPTION]...'
    echo ''
    echo '  -f, --force         Force re-register if ELS is already installed'
    echo '  -d, --delete        Delete ELS from server'
    echo '  -v, --validate      Check if ELS is installed'
    echo '  -h, --help          Show this message and exit'
}

els_installed() {
    echo "Checking if els-os-release is already installed... "
    if yum list installed els-os-release 2>/dev/null; then
        echo "els-os-release package is already installed."
        return 0
    fi
    return 1
}

install_els_os_release() {
    TEMP_RPM=$(mktemp /tmp/els-os-release-XXXXXX.rpm)

    trap 'rm -f "$TEMP_RPM"' EXIT

    if ! curl -fsSL -o "$TEMP_RPM" "$PACKAGE_URI"; then
        echo "Error: Couldn't download els-os-release.rpm"
        return 1
    fi

    # els-os-release depends on nothing outside rpmlib, so it needs no
    # repository: with every repo disabled a dead post-EOL mirror cannot abort
    # the install.
    if ! yum install -y --disablerepo='*' "$TEMP_RPM"; then
        echo "Error: Couldn't install els-os-release"
        return 3
    fi
}

check_rpm_version() {
    local package="$1"
    local required_version="$2"

    if ! rpm -q "$package" &>/dev/null; then
        echo "ERROR: $package is not installed"
        return 1
    fi

    local current_version=$(rpm -q --qf '%{VERSION}-%{RELEASE}' "$package")
    local comparison=$(rpm --eval "%{lua: print(rpm.vercmp('$current_version', '$required_version'))}")

    if [ "$comparison" -ge 0 ]; then
        return 0
    else
        return 1
    fi
}

check_arch() {
    local arch supported
    arch=$(uname -m)
    echo "Checking system architecture... ${arch}"
    for supported in ${SUPPORTED_ARCHES}; do
        if [[ "${arch}" == "${supported}" ]]; then
            return 0
        fi
    done
    echo "Error: Unsupported architecture '${arch}'. CentOS 7 ELS is available for: ${SUPPORTED_ARCHES}"
    return 1
}

check_eol_repos() {
    echo "Checking if server repositories are updated for post-EOL usage..."

    if ! check_rpm_version "nss-softokn" "3.90.0-1"; then
        echo "Error: Your system has an outdated version of 'nss-softokn'."
        echo "Required version: 3.90.0-1 or newer."
        echo ""
        echo "Please update the package by running:"
        echo "  yum update nss-softokn"
        echo ""
        echo "If you are unable to update, it is likely due to outdated or unreachable repositories."
        echo ""
        echo "To switch to supported vault repositories, run the following commands:"
        echo "  sed -i 's|mirror.centos.org|vault.centos.org|g' /etc/yum.repos.d/*.repo"
        echo "  sed -i 's|mirrorlist.centos.org|vault.centos.org|g' /etc/yum.repos.d/*.repo"
        echo "  sed -i 's|#baseurl=|baseurl=|g' /etc/yum.repos.d/*.repo"
        echo "  sed -i 's|mirrorlist=|#mirrorlist=|g' /etc/yum.repos.d/*.repo"
        echo ""
        echo "Then clean and rebuild the yum cache:"
        echo "  yum clean all && yum makecache"
        echo ""
        echo "After updating your repositories, try updating the package again:"
        echo "  yum update nss-softokn"
        echo ""
        echo "For detailed help, visit:"
        echo "   https://support.tuxcare.com/hc/en-us/articles/17220332955036"
        return 1
    fi

    echo "Repository accessibility check passed"
    return 0
}

remove_els_os_release() {
    echo "Removing els-os-release package... "
    if yum remove -y els-os-release; then
        echo "Ok"
    else
        echo "Error (Could not remove els-os-release package)"
        exit 1
    fi

    echo "Removing authentication configuration file... "
    if rm -f "$AUTH_CONF_PATH"; then
        echo "Ok"
    else
        echo "Error (Could not remove auth configuration file: $AUTH_CONF_PATH)"
        exit 1
    fi
}


check_superuser_privileges() {
    echo "Checking for superuser privileges..."
    if [ "$(id -u)" -ne 0 ]; then
        echo "Error: This script must be run with superuser privileges"
        return 1
    fi
    echo "Superuser privileges confirmed"
    return 0
}

# Walk the arguments with shift (iterating over a copy of "$@" while shifting
# lets the positional parameters drift).
while [[ $# -gt 0 ]]; do
    case "$1" in
        -f|--force)
            FORCE=true ; shift ;;
        -d|--delete)
            DELETE=true ; shift ;;
        -v|--validate)
            VALIDATE=true ; shift ;;
        -h|--help)
            show_usage ; exit 0 ;;
        -*)
            echo; echo "Unrecognized option: $1"; show_usage ; exit 1 ;;
        *)
            shift ;;
    esac
done

if ! check_superuser_privileges; then
    exit 14
fi
if [[ -n $VALIDATE ]]; then
    if els_installed; then
        echo "Server is registered"
        exit 0
    else
        echo "Server is not registered"
        exit 1
    fi
fi

if [[ -n $FORCE ]]; then
    if ! remove_els_os_release; then
        exit 1
    fi
fi

if [[ -n $DELETE ]]; then
    if ! remove_els_os_release; then
        exit 1
    fi
    echo "CentOS ELS deleted successfully"
    exit
fi

# check centos-release file
if [[ ! -f /etc/centos-release ]]; then
    echo "This server is not RHEL based"
    exit 1
fi

# check centos version
centos_release="$(cat /etc/centos-release)"
if [[ ! "${centos_release}" == *"CentOS Linux release 7.9"* ]]; then
    echo "This server is not CentOS Linux release 7.9"
    exit 1
fi

if ! check_arch; then
    exit 1
fi

if ! check_eol_repos; then
    exit 1
fi

# check if els is installed
if els_installed; then
    echo "This server has already installed ELS repo"
    echo "For re-registration run script with --force"
    exit 1
fi

# AUTH_CONF_PATH needs to be empty
if ! echo "" > "$AUTH_CONF_PATH"; then
    echo "Error: Could not write to $AUTH_CONF_PATH"
    exit 10
fi

install_els_os_release
INSTALL_RC=$?
if [[ $INSTALL_RC -ne 0 ]]; then
    rm -f "$AUTH_CONF_PATH"
    exit $INSTALL_RC
fi

yum clean all
echo "CentOS 7 ELS installed successfully"

