#!/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"
PACKAGE_URI="https://repo.tuxcare.com/rhel7-els/els-os-release-install.el7.x86_64.rpm"

# Temporary files
TEMP_RPM=""

exec 3>&1

cleanup() {
    if [[ -f "$TEMP_RPM" ]]; then
        rm -f "$TEMP_RPM"
    fi

    exec 3>&-
}

trap cleanup EXIT

log() {
    printf "%s\\n" "$1" 1>&3
}

show_usage() {
    echo 'Usage: install-rhel7-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'
}

do_opts() {
    if [ $# -eq 0 ]; then
        log "$(show_usage)"
        exit 1
    fi
    while [ $# -gt 0 ]; do
        key="$1"
        case $key in
            -h|--help)
                log "$(show_usage)"
                exit 0
                ;;
            -l|--license-key)
                if [[ -z "$2" || "$2" == -* ]]; then
                    log "Error: --license-key requires an argument"
                    log "$(show_usage)"
                    exit 1
                fi
                LICENSE="$2"
                shift
                ;;
            -f|--force)
                FORCE=true
                ;;
            -d|--delete)
                DELETE=true
                ;;
            -v|--validate)
                VALIDATE=true
                ;;
            -*|--*)
                log "Unknown option: $key"
                log "$(show_usage)"
                exit 1
                ;;
        esac
        shift
    done
}

els_installed() {
    log "Checking if els_os_release is already installed... "
    if rpm -q els-os-release > /dev/null 2>&1; then
        log "els-os-release package is already installed."
        return 0
    fi
    log "els-os-release package is not installed"
    return 1
}

extract_token() {
    if [ ! -f "$AUTH_CONF_PATH" ]; then
        log "ERROR: Auth config file not found at $AUTH_CONF_PATH"
        return 1
    fi

    token=$(cat "$AUTH_CONF_PATH")

    # Validate token
    if [[ -z "$token" || "$token" != *SERVER* ]]; then
        log "ERROR: Invalid token in $AUTH_CONF_PATH (empty or missing SERVER marker)"
        return 1
    fi

    echo "$token"
    return 0
}

unregister_token() {
    # The token to release: the argument, else the one in $AUTH_CONF_PATH
    local token=$1
    if [ -z "$token" ] && ! token=$(extract_token); then
        return 1
    fi

    log "Unregistering server token..."

    # The status comes from -w, never from the headers: behind a proxy the
    # first status line is the CONNECT reply "200 Connection established".
    response=$(curl -s -w '\n%{http_code}' -X POST "${CLN_UNREGISTER_SERVER}?token=${token}")
    curl_exit_code=$?

    if [ $curl_exit_code -ne 0 ]; then
        log "ERROR: Failed to connect to unregister server (curl exited with status: $curl_exit_code)"
        return 1
    fi

    local http_code body
    http_code=${response##*$'\n'}
    body=${response%$'\n'*}
    # 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 [ "$http_code" = "401" ] && [[ "$body" == *"not registered"* ]]; then
        log "Token is not registered in CLN any more; nothing to release"
        return 0
    fi
    if [ "$http_code" != "200" ]; then
        log "Got incorrect status from CLN: HTTP $http_code $body"
        return 1
    fi

    log "Unregistered successfully"
    return 0
}

# Release a registration left in $AUTH_CONF_PATH without the package (e.g.
# by a failed install), so it is neither overwritten nor kept forever.
release_authconf_token() {
    if [ ! -f "$AUTH_CONF_PATH" ]; then
        return 0
    fi
    if ! extract_token > /dev/null 2>&1; then
        log "Removing $AUTH_CONF_PATH: it holds no valid token"
        rm -f "$AUTH_CONF_PATH"
        return 0
    fi
    log "Releasing the registration held in $AUTH_CONF_PATH..."
    if ! unregister_token; then
        log "Warning: Could not release the registration from $AUTH_CONF_PATH"
        return 1
    fi
    rm -f "$AUTH_CONF_PATH"
    return 0
}

# Run a release_* function; a failure blocks a plain run (like any
# unregister failure) but only warns under --force.
checked_release() {
    "$1" && return 0
    if [ "$FORCE" != "true" ]; then
        log "Couldn't deactivate account"
        return 12
    fi
    log "Warning: Failed to unregister, but continuing due to --force"
    return 0
}

remove_els() {
    # Remove the ELS marker package installed from the ELS repo. It goes
    # before els-os-release, which carries the repo configuration. No repo is
    # needed to remove a package, and dead stock mirrors must not abort it.
    if rpm -q --quiet els-define; then
        log "Removing els-define package... "
        if yum remove -y --disablerepo='*' els-define 1>&3; then
            log "Removed els-define package successfully"
        else
            log "Error: Could not remove els-define package"
            return 1
        fi
    fi

    # This will remove repo configuration
    log "Removing els-os-release package... "
    if yum remove -y --disablerepo='*' els-os-release 1>&3; then
        log "Removed els-os-release package successfully"
    else
        log "Error: Could not remove els-os-release package"
        return 1
    fi

    log "Removing authentication configuration file... "
    if [[ -f "$AUTH_CONF_PATH" ]]; then
        if rm -f "$AUTH_CONF_PATH" 1>&3; then
            log "Removed authentication configuration file successfully"
        else
            log "Error: Could not remove auth configuration file: $AUTH_CONF_PATH"
            return 1
        fi
    else
        log "Auth configuration file not found"
    fi

    log "RHEL7 ELS deleted successfully"
    return 0
}

# Return codes: 12 = unregister failed (plain run), 13 = a leftover
# registration could not be released before registering again,
# 17 = the ELS packages or the token file could not be removed.
delete_els() {
    if els_installed; then
        if [ "$FORCE" = "true" ]; then
            # Force mode: try to unregister but continue even if it fails
            unregister_token || log "Warning: Failed to unregister, but continuing with force delete"
        else
            if ! unregister_token; then
                log "Couldn't deactivate account"
                return 12
            fi
        fi
        if ! remove_els; then
            return 17
        fi
    else
        # A failed install may have left its registration behind
        checked_release release_authconf_token || return $?
        # Under --force the file goes even if its registration was not
        # released, as on the installed path
        rm -f "$AUTH_CONF_PATH"
        log "ELS is not installed"
    fi
    log "ELS removal completed"
    return 0
}

get_auth_token() {
    log "Request repository token for this server... "
    local data="{\"key\": \"$3\", \"host_name\": \"$2\"}"
    local ret
    ret=$(curl -s -X POST -H "Content-Type: application/json" -H "Accept: application/json" -d "$data" "$1")
    if [ $? -ne 0 ]; then
        log "Error (Curl command failed)"
        return 1
    fi
    local token
    token=$(echo "$ret" | grep -oP '"token":"\K[^"]*')
    if [ -n "$token" ]; then
        log "Ok"
        echo "$token"
        return 0
    fi
    log "Error (No token was returned from CLN)"
    return 1
}

install_els() {
    log "Installing els-os-release..."

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

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

    # els-os-release depends on nothing outside rpmlib, so it needs no repo to
    # resolve against; with dead stock mirrors the metadata refresh would
    # otherwise abort the install after the server was registered.
    if ! yum install -y --disablerepo='*' "$TEMP_RPM"; then
        log "Error: Couldn't install els-os-release"
        return 3
    fi

    log "els-os-release installed successfully"
    return 0
}

check_system_compatibility() {
    log "Checking system compatibility..."

    if [[ ! -f /etc/redhat-release ]]; then
        log "This server is not RHEL based"
        return 1
    fi

    # check rhel version
    rhel_release="$(cat /etc/redhat-release)"
    if [[ ! "${rhel_release}" == *"Red Hat Enterprise Linux Server release 7"* ]]; then
        log "This server is not Red Hat Enterprise Linux Server release 7"
        exit 1
    fi

    if ! command -v curl &> /dev/null; then
        log "Error: curl is required but not installed"
        return 1
    fi

    log "System compatibility check passed"
}

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

main() {
    do_opts "$@"

    if ! check_superuser_privileges; then
        return 14
    fi

    if ! check_system_compatibility; then
        return 1
    fi

    if [ "$DELETE" = "true" ];  then
        delete_els
        return $?
    fi

    if [[ "$VALIDATE" = "true" ]]; then
        if els_installed; then
            log "Server is registered with token $(cat /etc/yum/vars/elstoken)"
            exit 0
        else
            log "Server is not registered"
            exit 1
        fi
    fi

    if [[ -z $LICENSE ]]; then
        log "License key should be specified with -l, --license-key."
        log "See -h, --help."
        return 1
    fi

    local token registered=""
    if els_installed; then
        if [ "$FORCE" = "true" ]; then
            # Make before break: register the new key first, so a rejected
            # key or an unreachable CLN leaves the working install untouched
            local old_token
            old_token=$(extract_token 3>/dev/null) || old_token=""
            log "Registering in CLN..."
            if ! token=$(get_auth_token "$CLN_REGISTER_SERVER" "$HOSTNAME" "$LICENSE"); then
                log "Nothing was changed. If the licence has no free seat, run with --delete first, then install again."
                return 3
            fi
            registered=true
            # Remove first: if that fails the host keeps a working install
            # with a live token, and only the new registration is released
            if ! remove_els; then
                # Do not leave the new registration behind
                if [ "$token" != "$old_token" ]; then
                    unregister_token "$token" || log "Warning: Could not release the new registration"
                fi
                return 17
            fi
            # CLN may hand this host its old token again: that seat stays
            if [ -n "$old_token" ] && [ "$old_token" != "$token" ]; then
                unregister_token "$old_token" || log "Warning: Failed to unregister the old token, but continuing due to --force"
            fi
        else
            log "This server has installed ELS repo and token"
            log "For re-registration license run script with --force"
            return 2
        fi
    elif ! checked_release release_authconf_token; then
        # A failed install left a registration behind; registering again
        # would overwrite the only handle on it
        log "Run with --delete to release it, then install again"
        return 13
    fi

    if [ "$registered" != "true" ]; then
        log "Registering in CLN..."
        token=$(get_auth_token "$CLN_REGISTER_SERVER" "$HOSTNAME" "$LICENSE")
        if [ $? -ne 0 ]; then
            return 3
        fi
    fi

    if ! echo "${token}" > "$AUTH_CONF_PATH"; then
        log "Error (Could not write to $AUTH_CONF_PATH)"
        # Nothing else holds the new token: release its seat now
        unregister_token "$token"
        return 10
    fi

    log "Applying repository token for this server..."
    if ! install_els; then
        # Release the registration just made instead of leaving it behind;
        # if that fails the token file stays for a later -d to release.
        release_authconf_token
        return 9
    fi

    yum clean all
    if ! yum install -y els-define --disablerepo=* --enablerepo=rhel7-els; then
        log "Error: Couldn't install els-define"
        return 1
    fi

    log "ELS installed successfully"
}

main "$@"
