#!/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/phpelstoken"
ALT_COMMON_PACKAGE_URI="https://repo.alt.tuxcare.com/alt-common/alt-common-release-install.x86_64.rpm"
PACKAGE_URI="https://repo.alt.tuxcare.com/alt-php-els/els-php-release-install.x86_64.rpm"


exec 3>&1
trap "exec 3>&-" EXIT

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

show_usage() {
    echo 'Usage: install-php-els-ubuntu-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 '  -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)
                LICENSE="$2"
                shift
                ;;
            -f|--force)
                FORCE=true
                ;;
            -d|--delete)
                DELETE=true
                ;;
            -*|--*)
                log "Unknown option: $key"
                log "$(show_usage)"
                exit 1
                ;;
        esac
        shift
    done

    if [ -z "$LICENSE" ] && [ "$DELETE" != "true" ]; then
        log "Required argument not provided: --license-key"
        log "$(show_usage)"
        exit 1
    fi
}

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

unregister_token() {
    token=$(cat "$AUTH_CONF_PATH")
    response=$(curl -i -s -X POST "${CLN_UNREGISTER_SERVER}?token=${token}")
    curl_exit_code=$?

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

    if ! echo "$response" | grep -qi '^HTTP/[0-9.].*200.*OK'; then
        if [[ -z "$response" ]]; then
            echo "elstoken wasn't found. Server is not registered"
        else
            echo "Got incorrect status from CLN: $response"
        fi
        return 1
    fi

    echo "Unregistered successfully"
    return 0
}

remove_els() {
    # This will remove repo configuration
    log "Removing els-php-release package... "
    if yum remove -y els-php-release 1>&3; then
        log "Ok"
    else
        log "Error (Could not remove els-php-release package)"
        return 1
    fi

    log "Removing authentication configuration file... "
    if rm -f "$AUTH_CONF_PATH" 1>&3; then
        log "Ok"
    else
        log "Error (Could not remove auth configuration file: $AUTH_CONF_PATH)"
        return 1
    fi

    log "PHP ELS deleted successfully"
}

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_alt_common_release() {
    log "Checking if alt-common-release is already installed... "
    if rpm -q alt-common-release 2>/dev/null; then
        log "alt-common-release package is already installed."
        return 0
    fi
    log "Installing alt-common-release..."

    ALT_COMMON_TEMP_RPM=$(mktemp /tmp/alt-common-releaseXXXXXX.rpm)

    if ! curl -fsSL -o "$ALT_COMMON_TEMP_RPM" "$ALT_COMMON_PACKAGE_URI"; then
        log "Error: Couldn't download alt-common-release.rpm"
        return 1
    fi

    if ! yum install -y "$ALT_COMMON_TEMP_RPM"; then
        log "Error: Couldn't install alt-common-release"
        return 3
    fi

    log "alt-common-release installed successfully"
    return 0
}

install_els_php_release() {
    if ! install_alt_common_release; then
        return 2
    fi
    log "Installing els-php-release..."

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

    trap 'rm -f "$TEMP_RPM"' EXIT

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

    if ! yum install -y "$TEMP_RPM"; then
        log "Error: Couldn't install els-php-release"
        return 3
    fi
}

validate_supported_os() {
    # Check if the system is RHEL-based
    if [[ -f /etc/redhat-release ]]; then
        log "Detected RHEL-based system"
        return 0
    fi

    # Check for Amazon Linux 2 specifically
    if grep -qi "Amazon Linux release 2" /etc/system-release 2>/dev/null; then
        log "Detected Amazon Linux 2"
        return 0
    fi

    return 1
}

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() {
    if ! check_superuser_privileges; then
        return 14
    fi

    do_opts "$@"

    if ! validate_supported_os; then
        log "Unsupported OS detected"
        return 1
    fi

    if [ "$DELETE" = "true" ];  then
        if els_installed; then
            if ! unregister_token; then
                log "Couldn't deactivate account"
                return 12
            fi
            remove_els
        else
            log "ELS is not installed"
        fi
        return 0
    fi

    if els_installed; then
        if [ "$FORCE" = "true" ]; then
            unregister_token
            remove_els
        else
            log "This server has installed ELS repo and token"
            log "For re-registration license run script with --force"
            return 2
        fi
    fi

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

    AUTH_CONF_DIR=$(dirname "$AUTH_CONF_PATH")
    mkdir -p "$AUTH_CONF_DIR"

    if ! echo "${token}" > "$AUTH_CONF_PATH"; then
        log "Error (Could not write to $AUTH_CONF_PATH)"
        return 10
    fi

    log "Applying repository token for this server..."
    if ! install_els_php_release; then
        return 9
    fi

    log "ELS for PHP installed successfully"
}

main "$@"
