#!/usr/bin/env bash

CLN_REGISTER_SERVER="https://cln.cloudlinux.com/cln/api/els/server/register"
CLN_UNREGISTER_SERVER="https://cln.cloudlinux.com/cln/api/els/server/unregister"
LICENSE=""
HOSTNAME=`hostname`
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
# registering 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.sh [OPTION]...'
    echo ''
    echo '  -l, --license-key   User license key'
    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 is already installed... "

    # Check for new installation method (els-os-release package)
    if yum list installed els-os-release 2>/dev/null; then
        echo "els-os-release package is already installed."
        return 0
    fi

    # Check for old installation method (elstoken file and repo files)
    if [[ -f "$AUTH_CONF_PATH" || -f /etc/yum.repos.d/centos7-els.repo ]]; then
        echo "ELS is installed using the old installation method."
        return 0
    fi

    return 1
}

get_current_token() {
    # Both the package-based and the legacy install keep the token in the
    # elstoken yum variable.
    if [[ -f "$AUTH_CONF_PATH" ]]; then
        cat "$AUTH_CONF_PATH"
    fi
}

# Unregister $1 (default: the token on disk).
# Returns: 0 - unregistered or unknown to CLN, 1 - unregister failed, 2 - no token found
unregister_server() {
    # local: --force releases the old token after the new one is in $TOKEN
    local TOKEN=${1:-$(get_current_token)}
    if [[ -z "$TOKEN" ]]; then
        echo "No token found - server may not be registered"
        return 2
    fi

    echo "Attempting to unregister server..."
    # Take the status from curl, not from the response text: behind an HTTPS
    # proxy the first status line is the proxy's "200 Connection established".
    CLN_UNREGISTER=$(curl -s -w '\n%{http_code}' -X POST "$CLN_UNREGISTER_SERVER?token=$TOKEN")
    CLN_UNREGISTER_CODE=${CLN_UNREGISTER##*$'\n'}
    if [[ "$CLN_UNREGISTER_CODE" == "200" ]]; then
        echo "Server unregistered successfully"
        return 0
    fi
    # CLN answers 401 "Token not registered as an ELS server" for a token it no
    # longer knows (released in the portal, expired licence): no seat is held.
    if [[ "$CLN_UNREGISTER_CODE" == "401" && "${CLN_UNREGISTER%$'\n'*}" == *"not registered"* ]]; then
        echo "Token is not registered in CLN any more; nothing to release"
        return 0
    fi

    echo "Warning: Failed to unregister server (HTTP $CLN_UNREGISTER_CODE): ${CLN_UNREGISTER%$'\n'*}"
    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 after the server was already registered.
    if ! yum install -y --disablerepo='*' "$TEMP_RPM"; then
        echo "Error: Couldn't install els-os-release"
        return 3
    fi
}

remove_els_installation() {
    # Hosts enrolled while this script still installed els-define may carry it;
    # remove it before the repo config so yum can still resolve it.
    if rpm -q --quiet els-define; then
        echo "Removing els-define package... "
        if yum remove -y --disablerepo='*' els-define; then
            echo "Ok"
        else
            echo "Error (Could not remove els-define package)"
            return 1
        fi
    fi

    # Remove new installation method (els-os-release package)
    if yum list installed els-os-release 2>/dev/null; then
        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)"
            return 1
        fi
    fi

    # Remove old installation method files
    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)"
        return 1
    fi

    echo "Removing old repository configuration files... "
    if ! rm -f /etc/yum.repos.d/centos7-els.repo; then
        echo "Error (Could not remove centos7-els.repo)"
        return 1
    fi

    if ! rm -f /etc/yum.repos.d/centos7-els-rollout.repo; then
        echo "Error (Could not remove centos7-els-rollout.repo)"
        return 1
    fi
}

# Exit after a failed registration. On --force nothing has been touched yet.
register_failed() {
    echo "$1"
    if [[ -n $FORCE ]]; then
        echo "Nothing was changed. If the licence has no free seat, run with --delete first, then install again."
    fi
    exit 1
}

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
}

if [[ $# -eq 0 ]]; then
    echo "An option should be specified. See usage -h, --help."
    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
# made $2 lag behind, so "-l" could pick up the wrong word as the key.
while [[ $# -gt 0 ]]; do
    case "$1" in
        -l|--license-key)
            if [[ -z "$2" || "$2" == -* ]]; then
                echo "Error: --license-key requires an argument"
                show_usage
                exit 1
            fi
            LICENSE=$2 ; shift 2 ;;
        -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
        if [[ -f "$AUTH_CONF_PATH" ]]; then
            TOKEN=$(cat "$AUTH_CONF_PATH")
            if [[ -n "$TOKEN" ]]; then
                echo "Server is registered with token $TOKEN"
            else
                echo "Server is registered but token file is empty"
            fi
        else
            echo "Server is registered but token file not found"
        fi
        exit 0
    else
        echo "Server is not registered"
        exit 1
    fi
fi

if [[ -n $DELETE ]]; then
    # Attempt to unregister from server (if token exists)
    unregister_server
    UNREGISTER_RC=$?

    # The token is the only handle on the CLN seat: keep it unless CLN
    # confirmed the release, or the caller insists with --force.
    if [[ $UNREGISTER_RC -eq 1 && -z $FORCE ]]; then
        echo "Couldn't deactivate account; nothing was removed"
        echo "Re-run with --delete --force to remove ELS from this server anyway"
        exit 12
    fi

    echo "Removing ELS installation..."
    if ! remove_els_installation; then
        exit 1
    fi

    if [[ $UNREGISTER_RC -eq 0 ]]; then
        echo "CentOS ELS deleted successfully"
    elif [[ $UNREGISTER_RC -eq 2 ]]; then
        echo "CentOS ELS removed successfully (server was not registered)"
    else
        echo "CentOS ELS removed successfully, but the server could not be unregistered from CLN"
    fi
    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 license key
if [[ -z $LICENSE ]]; then
    echo "License key should be specified with -l, --license-key."
    echo "See -h, --help."
    exit 1
fi

# check if els is installed
if [[ -n $FORCE ]]; then
    # Force re-registration is make-before-break: the new key is registered
    # first and the previous installation is torn down only once CLN has
    # accepted it, so a rejected key or an unreachable CLN changes nothing.
    OLD_TOKEN=$(get_current_token)
elif els_installed; then
    echo "This server has already installed ELS repo and token"
    echo "For re-registration license run script with --force"
    exit 1
fi

# get token
CLN_REGISTER=$(curl -s -w '\n%{http_code}' -X POST -H "Content-Type: application/json" -H "accept: */*" -d "{\"key\": \"$LICENSE\", \"host_name\": \"$HOSTNAME\"}" "$CLN_REGISTER_SERVER")
CLN_CODE=${CLN_REGISTER##*$'\n'}
CLN_REGISTER=${CLN_REGISTER%$'\n'*}

if [[ "$CLN_CODE" != "200" ]]; then
    register_failed "Got incorrect status from CLN (HTTP $CLN_CODE): $CLN_REGISTER"
fi

TOKEN=$(echo "$CLN_REGISTER" | grep -oP '"token":"\K[\w\d-]*')

if [[ -z $TOKEN ]]; then
    register_failed "Something went wrong. Token is not defined"
fi

if [[ -n $FORCE ]]; then
    # Remove the previous installation, complete or partial, then release its
    # token (or its CLN seat would stay taken) and proceed as a fresh install.
    # Removal comes first so that, if it fails, the host keeps a working
    # install with a live token. CLN may hand this host the same token again,
    # which stays.
    if ! remove_els_installation; then
        # CLN may have handed back the token the remaining install still uses
        if [[ "$OLD_TOKEN" != "$TOKEN" ]]; then
            echo "Releasing the registration issued for this install..."
            unregister_server "$TOKEN"
        fi
        exit 1
    fi
    if [[ -n $OLD_TOKEN && "$OLD_TOKEN" != "$TOKEN" ]]; then
        unregister_server "$OLD_TOKEN"
    fi
fi

if ! echo "${TOKEN}" > "$AUTH_CONF_PATH"; then
    echo "Error: Could not write to $AUTH_CONF_PATH"
    unregister_server "$TOKEN"
    exit 10
fi

# A failed install must not keep the seat CLN has just issued, nor leave a
# token that makes the next run refuse with "already installed".
install_els_os_release
INSTALL_RC=$?
if [[ $INSTALL_RC -ne 0 ]]; then
    echo "Releasing the registration issued for this install..."
    if unregister_server "$TOKEN"; then
        rm -f "$AUTH_CONF_PATH"
    else
        # The token file is the only handle on that seat: keep it
        echo "Keeping $AUTH_CONF_PATH; run with --delete to release it, then install again"
    fi
    exit $INSTALL_RC
fi

yum clean all
echo "CentOS 7 ELS installed successfully"

