#!/bin/bash

HOSTNAME=$(hostname)
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"

# Temporary files
ALT_COMMON_TEMP_DEB=""
TEMP_DEB=""

exec 3>&1

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

    if [[ -f "$ALT_COMMON_TEMP_DEB" ]]; then
        rm -f "$ALT_COMMON_TEMP_DEB"
    fi

    exec 3>&-
}

trap cleanup EXIT

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

show_usage() {
    echo 'Usage: install-els-alt-php-deb-repo-ip.sh [OPTION]...'
    echo ''
    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() {
    while [ $# -gt 0 ]; do
        key="$1"
        case $key in
            -h|--help)
                log "$(show_usage)"
                exit 0
                ;;
            -f|--force)
                FORCE=true
                ;;
            -d|--delete)
                DELETE=true
                ;;
            -v|--validate)
                VALIDATE=true
                ;;
            -*|--*)
                log "Unknown option: $key"
                log "$(show_usage)"
                exit 1
                ;;
        esac
        shift
    done
}

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 1
    fi
    . "$os_release_path"
    if [ -z "$ID" ]; then
        log "Error (Could not determine OS: ID not found in $os_release_path)"
        return 1
    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
}

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"
}

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)

    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
}

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
}

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

    distro=$(get_distro_name)
    if [ "$distro" != "debian" ] && [ "$distro" != "ubuntu" ]; then
        log "Detected unsupported distro: $distro"
        return 11
    fi

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

    log "System compatibility check passed"
}

main() {
    do_opts "$@"

    if [ "$VALIDATE" = "true" ]; then
        if els_installed; then
            log "Server is registered"
            return 0
        else
            log "Server is not registered"
            return 1
        fi
    fi

    if ! check_superuser_privileges; then
        return 14
    fi

    if ! check_system_compatibility; then
        return 1
    fi

    if [ "$DELETE" = "true" ];  then
        if els_installed; then
            remove_els
        else
            log "ELS is not installed"
        fi
        return 0
    fi

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

    log "Installing ELS for PHP with IP-based licensing..."
    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 "$@"

