#!/bin/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/apt/auth.conf.d/php-els.conf"
PHP_REPO_PATH="/etc/apt/sources.list.d/php-els.list"
ALT_COMMON_PACKAGE_URI="https://repo.alt.tuxcare.com/alt-common/alt-common-release-install.amd64.deb"
PACKAGE_URI="https://repo.alt.tuxcare.com/alt-php-els/els-php-release-install.amd64.deb"


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

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

show_usage() {
    echo 'Usage: install-php-els-deb-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

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

get_distro_name() {
    local os_release_path="/etc/os-release"
    log "Get OS info... "
    if [ ! -f "$os_release_path" ]; then
        log "Error (Could not determine OS: $os_release_path does not exist)"
        return 0
    fi
    . "$os_release_path"
    if [ -z "$ID" ]; then
        log "Error (Could not determine OS: ID not found in $os_release_path)"
        return 0
    fi
    echo "$ID"
    return 0
}

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

extract_token() {
    # Case 1: clients use old way
    token=$(sed -n 's|.*php-els/\([^/]*\)/.*|\1|p' "$PHP_REPO_PATH")

    if [[ -z "$token" || "$token" != *SERVER* ]]; then
        log "Couldn't extract token from $PHP_REPO_PATH, trying from $AUTH_CONF_PATH"
        # Case 2: clients use new way
        token=$(sed -n 's/^login \([^[:space:]]*\).*/\1/p' "$AUTH_CONF_PATH")

        if [[ -z "$token" || "$token" != *SERVER* ]]; then
            log "Couldn't extract token from $AUTH_CONF_PATH"
            return 1
        fi
    fi

    echo "$token"
    return 0
}


unregister_token() {
    if ! token=$(extract_token); then
        return 1
    fi

    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 "DELETE: 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 "Purging els-php-release package... "
    if apt-get purge -yq els-php-release 1>&3; then
        log "Ok"
    else
        log "Error (Could not purge els-php-release package)"
        return 1
    fi

    log "PHP ELS deleted successfully"
    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
}

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 dpkg -l alt-common-release >/dev/null 2>&1; then
        log "alt-common-release package is already installed."
        return 0
    fi
    log "Installing alt-common-release..."

    ALT_COMMON_TEMP_DEB=$(mktemp /tmp/alt-common-releaseXXXXXX.deb)

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

    if ! dpkg -i "$ALT_COMMON_TEMP_DEB"; then
        log "Error: Couldn't install alt-common-release"
        return 3
    fi

    return 0
}

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

    TEMP_DEB=$(mktemp /tmp/els-php-release-XXXXXX.deb)

    trap 'rm -f "$TEMP_DEB"' EXIT

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

    if ! dpkg -i "$TEMP_DEB"; then
        log "Error: Couldn't install els-php-release"
        return 3
    fi
}

main() {
    do_opts "$@"

    distro=$(get_distro_name)
    if [ "$distro" != "debian" ] && [ "$distro" != "ubuntu" ]; then
        log "Detected unsupported distro: $distro"
        return 11
    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

    if ! echo -e "machine repo.alt.tuxcare.com/alt-php-els/\nlogin $token\npassword" > "$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 "Updating cache..."
    if ! apt-get -yq update 1>&3; then
        log "Error (Could not update repository cache)"
        return 6
    fi

    log "ELS for PHP installed successfully"
}

main "$@"
