#!/usr/bin/env bash
#
# Name: kInit
# Author: Kleb
# Created: 2021/12/23
# Last modified: 2025/12/01
#
# Version: 3.0
#

export LC_ALL=C.UTF-8
export LANG=C.UTF-8

set -euo pipefail

currentName="kInit"
currentVersion="3.0"
currentMe="$(basename "$0")"

skipChecksum="FALSE"
debugMode="FALSE"
continueOnError="FALSE"

BASE_URL="${BASE_URL:-https://kleb.sh}"
locationUtils="$BASE_URL/installer/utils.sh"
locationVars="$BASE_URL/kInit.vars"

start() {
    clear

    if ! wget -q -O "utils.sh" "$locationUtils"; then
        printf "Failed to download utils.sh"
        exit 1
    fi

    source "utils.sh"

    trap restoreCursor EXIT
    trap clean ERR

    toggleCursor

    printf "${colors[CYAN]}"
    printf "+=========================================+\n"
    printf "|  kInit Version: $currentVersion                     |\n"
    printf "|  System Installation & Setup Assistant  |\n"
    printf "|                                         |\n"
    printf "|  ${colors[BOLD]}${colors[MAGENTA]}      @@@@@  @@@@      ${colors[RESET]}${colors[CYAN]}                |\n"
    printf "|  ${colors[BOLD]}${colors[MAGENTA]}    @@@  @@@@@   @@@   ${colors[RESET]}${colors[CYAN]}                |\n"
    printf "|  ${colors[BOLD]}${colors[MAGENTA]}   @@@@@@ @@@@@@@@@@@@ ${colors[RESET]}${colors[CYAN]}                |\n"
    printf "|  ${colors[BOLD]}${colors[MAGENTA]}  @@       @@@@  @@  @ ${colors[RESET]}${colors[CYAN]}                |\n"
    printf "|  ${colors[BOLD]}${colors[MAGENTA]}  @@ @@ @@ @@   @@@@@@ ${colors[RESET]}${colors[CYAN]}                |\n"
    printf "|  ${colors[BOLD]}${colors[MAGENTA]}    @@@@@     @@   @@@ ${colors[RESET]}${colors[CYAN]}                |\n"
    printf "|  ${colors[BOLD]}${colors[MAGENTA]}      @@@@@@@@   @@@   ${colors[RESET]}${colors[CYAN]}                |\n"
    printf "|  ${colors[BOLD]}${colors[MAGENTA]}             @@ @@     ${colors[RESET]}${colors[CYAN]}                |\n"
    printf "|  ${colors[BOLD]}${colors[MAGENTA]}              @@@@     ${colors[RESET]}${colors[CYAN]}                |\n"
    printf "|                                         |\n"
    printf "|       Sanity is overrated               |\n"
    printf "|          klebHosting                    |\n"
    printf "|                                         |\n"
    printf "|  Created by: kleb                       |\n"
    printf "|  Feedback: feedback@kleb.dev            |\n"
    printf "+=========================================+\n"
    printf "${colors[RESET]}\n\n"


    if [[ $(id -u) -ne 0 ]]; then
        printf "${colors[RED]}Please run as root.${colors[RESET]}\n"
        exit 1
    fi

    if [[ -n "${BASH_XTRACEFD+set}" ]]; then
        printf "${colors[RED]}Running scripts in DEBUG${colors[RESET]}\n"

        debugMode=$TRUE
    fi

    prepare "$@"
    execute
    clean
}

prepare() {
    initProgress "kInit"
    updateProgress "Preparing installation" 5

    while [[ $# -gt 0 ]]; do
        case "$1" in
        --system-url | -s)
            SYSTEM_URL="$2"
            logInfo "Setting SYSTEM_URL to $2"
            shift 2
            ;;
        --utilities-url | -u)
            UTILITIES_URL="$2"
            logInfo "Setting UTILITIES_URL to $2"
            shift 2
            ;;
        --software-url | -w)
            SOFTWARE_URL="$2"
            logInfo "Setting SOFTWARE_URL to $2"
            shift 2
            ;;
        --miscellaneous-url | -m)
            MISCELLANEOUS_URL="$2"
            logInfo "Setting MISCELLANEOUS_URL to $2"
            shift 2
            ;;
        --base-url | -b)
            BASE_URL="$2"
            logInfo "Setting BASE_URL to $2"
            shift 2
            ;;
        --checksum-url | -c)
            CHECKSUM_URL="$2"
            logInfo "Setting CHECKSUM_URL to $2"
            shift 2
            ;;
        --skip-checksums | -sc)
            skipChecksum=$TRUE
            export skipChecksum
            logInfo "Skipping checksum verification"
            shift
            ;;
        --continue-on-error | -ce)
            continueOnError=$TRUE
            export continueOnError
            logInfo "Continuing on error"
            shift
            ;;
        --help | -h)
            help
            ;;
        *)
            printf "${colors[RED]}Unknown option: %s${colors[RESET]}\n\n" "$1"
            help
            ;;
        esac
    done

    if ! download "$locationVars" "kInit.vars" $TRUE; then
        printf "${colors[RED]}Failed to download kInit.vars${colors[RESET]}\n"
        exit 1
    fi

    source "kInit.vars"

    if ! download "$CHECKSUM_URL" "checksums.sha256" $TRUE; then
        printf "${colors[RED]}Failed to download checksums.sha256${colors[RESET]}\n"
        exit 1
    fi

    cleanAptSources
    runWithSpinner "Updating package list..." "apt update" "" "Updated package list"
}

execute() {
    updateProgress "Installing components 1/4" 10

    if [[ "$SYSTEM_EXECUTE" == "TRUE" ]]; then
        if ! download "$SYSTEM_URL" "system.sh" "$skipChecksum"; then
            logError "Failed to download system script"
            if [[ "$continueOnError" != "TRUE" ]]; then
                return 1
            fi
        fi

        if ! executeScript "system.sh" $debugMode "kInit"; then
            logError "Failed to execute system script"
            if [[ "$continueOnError" != "TRUE" ]]; then
                return 1
            fi
        fi
    fi

    updateProgress "Installing components 2/4" 35

    if [[ "$UTILITIES_EXECUTE" == "TRUE" ]]; then
        if ! download "$UTILITIES_URL" "utilities.sh" "$skipChecksum"; then
            logError "Failed to download utilities script"
            if [[ "$continueOnError" != "TRUE" ]]; then
                return 1
            fi
        fi

        if ! executeScript "utilities.sh" $debugMode "kInit"; then
            logError "Failed to execute utilities script"
            if [[ "$continueOnError" != "TRUE" ]]; then
                return 1
            fi
        fi
    fi

    updateProgress "Installing components 3/4" 60

    if [[ "$SOFTWARE_EXECUTE" == "TRUE" ]]; then
        if ! download "$SOFTWARE_URL" "software.sh" "$skipChecksum"; then
            logError "Failed to download software script"
            if [[ "$continueOnError" != "TRUE" ]]; then
                return 1
            fi
        fi

        if ! executeScript "software.sh" $debugMode "kInit"; then
            logError "Failed to execute software script"
            if [[ "$continueOnError" != "TRUE" ]]; then
                return 1
            fi
        fi
    fi

    updateProgress "Installing components 4/4" 85

    if [[ "$MISCELLANEOUS_EXECUTE" == "TRUE" ]]; then
        if ! download "$MISCELLANEOUS_URL" "miscellaneous.sh" "$skipChecksum"; then
            logError "Failed to download miscellaneous script"
            if [[ "$continueOnError" != "TRUE" ]]; then
                return 1
            fi
        fi

        if ! executeScript "miscellaneous.sh" $debugMode "kInit"; then
            logError "Failed to execute miscellaneous script"
            if [[ "$continueOnError" != "TRUE" ]]; then
                return 1
            fi
        fi
    fi
}

clean() {
    remove "kInit.vars"
    remove "utils.sh"
    remove "checksums.sha256"
    remove "$currentMe"

    updateProgress "Installation complete" 100
}

help() {
    printf "${colors[CYAN]}Usage: %s [options]${colors[RESET]}\n" "$0"
    printf "${colors[WHITE]}Options:${colors[RESET]}\n"
    printf "    ${colors[YELLOW]}--system-url, -s ${colors[WHITE]}<url>       - Specify the URL of the main system file${colors[RESET]}\n"
    printf "    ${colors[YELLOW]}--utilities-url, -u ${colors[WHITE]}<url>        - Specify the URL of the main utilities file${colors[RESET]}\n"
    printf "    ${colors[YELLOW]}--software-url, -w ${colors[WHITE]}<url>     - Specify the URL of the main software file${colors[RESET]}\n"
    printf "    ${colors[YELLOW]}--miscellaneous-url, -m ${colors[WHITE]}<url>         - Specify the URL of the main miscellaneous file${colors[RESET]}\n"
    printf "    ${colors[YELLOW]}--base-url, -b ${colors[WHITE]}<url>             - Specify the base URL (default: https://kleb.sh)${colors[RESET]}\n"
    printf "    ${colors[YELLOW]}--checksum-url, -c ${colors[WHITE]}<url>         - Specify the URL of the checksum file${colors[RESET]}\n"
    printf "\n"
    printf "    ${colors[YELLOW]}--skip-checksums, -sc${colors[WHITE]}        - Skip checksum verification for downloads${colors[RESET]}\n"
    printf "    ${colors[YELLOW]}--continue-on-error, -ce${colors[WHITE]}  - Continue execution even if commands fail${colors[RESET]}\n"
    printf "\n"
    printf "    ${colors[YELLOW]}--help, -h ${colors[WHITE]}                 - Display this help message${colors[RESET]}\n"

    exit 0
}

start "$@"

