#!/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-els-alt-php-rpm-repo.sh [OPTION]...'
    echo ''
    echo '  -l, --license-key   User license key'
    echo '  -i, --imunify       Use Imunify360 license for repository access.'
    echo '                      Only available when Imunify360 is installed on this system'
    echo '                      and has a valid license. Do not use otherwise.'
    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)
                if [[ -z "$2" || "$2" == -* ]]; then
                    log "Error: --license-key requires an argument"
                    log "$(show_usage)"
                    exit 1
                fi
                LICENSE="$2"
                shift
                ;;
            -i|--imunify)
                IMUNIFY=true
                ;;
            -f|--force)
                FORCE=true
                ;;
            -d|--delete)
                DELETE=true
                ;;
            -*|--*)
                log "Unknown option: $key"
                log "$(show_usage)"
                exit 1
                ;;
        esac
        shift
    done

    # For install: require either --license-key or --imunify (protection from accidental run without credentials)
    if [ "$DELETE" != "true" ] && [ -z "$LICENSE" ] && [ "$IMUNIFY" != "true" ]; then
        log "Must specify either --license-key or --imunify for installation."
        log "Use --imunify only on systems where Imunify360 is installed with a valid license."
        log "$(show_usage)"
        exit 1
    fi
    if [ -n "$LICENSE" ] && [ "$IMUNIFY" = "true" ]; then
        log "Cannot use --license-key and --imunify together. Choose one."
        log "$(show_usage)"
        exit 1
    fi
}

# Get Imunify360 license id from imunify360-agent (for --imunify mode).
get_imunify_license_id() {
    local tmp id
    if ! command -v imunify360-agent >/dev/null 2>&1; then
        return 1
    fi
    tmp=$(mktemp) || return 1
    # Only stdout (JSON) to file; stderr (warnings) to /dev/null so JSON stays valid
    imunify360-agent version --json >"$tmp" 2>/dev/null || { rm -f "$tmp"; return 1; }
    id=$(python3 -c "
import json, sys
try:
    with open(sys.argv[1]) as f:
        d = json.load(f)
    lid = (d.get('license') or {}).get('id') or ''
    if lid:
        print(lid)
except Exception:
    pass
" "$tmp" 2>/dev/null)
    rm -f "$tmp"
    if [ -n "$id" ]; then
        echo "$id"
        return 0
    fi
    return 1
}

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.]*[[:space:]]200'; then
        if [ -z "$response" ]; then
            echo "elstoken wasn't found. Server is not registered"
        elif echo "$response" | grep -qi "wasn't found\|not registered"; then
            echo "Token not registered in CLN; proceeding with removal"
            return 0
        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"
}

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"
            remove_els
        else
            if ! unregister_token; then
                log "Couldn't deactivate account"
                return 12
            fi
            remove_els
        fi
    else
        log "ELS is not installed"
    fi
    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_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
        rm -f "$ALT_COMMON_TEMP_RPM"
        log "Error: Couldn't install alt-common-release"
        return 3
    fi

    rm -f "$ALT_COMMON_TEMP_RPM"
    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
        delete_els
        return $?
    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

    local token
    if [ "$IMUNIFY" = "true" ]; then
        log "Using Imunify360 license for repository access..."
        token=$(get_imunify_license_id)
        if [ -z "$token" ]; then
            log "Error: Imunify360 is not installed on this system or has no valid license."
            log "Install Imunify360 with a valid license, or use --license-key for standard installation."
            return 1
        fi
        log "Ok"
    else
        log "Registering in CLN..."
        if ! token=$(get_auth_token "$CLN_REGISTER_SERVER" "$HOSTNAME" "$LICENSE"); then
            return 3
        fi
    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 "$@"
