#!/usr/bin/env bash
#
# Name: Miscellaneous Installer
# Author: kleb
# Created: 2024/11/12
# Last modified: 2025/12/01
#
# Version: 1.4
#

set -euo pipefail

currentName="Miscellaneous Installer"
currentVersion="1.4"
currentMe="$(basename "$0")"

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

parentModule="${1:-}"

start() {
    source "utils.sh"

    trap clean ERR

    initProgress "Miscellaneous" "$parentModule"
    logInfo "$currentName v$currentVersion"

    prepare
    execute
    clean
}

prepare() {
    updateProgress "Preparing Miscellaneous module" 5

    if ! download "$locationVars" "miscellaneous.vars" "${skipChecksum:-}"; then
        logError "Failed to download miscellaneous.vars"
        return 1
    fi

    source "miscellaneous.vars"
}

execute() {
    updateProgress "Running system update script" 30

    if [[ "${RUN_UPDATE:-}" == "TRUE" ]]; then
        if ! runWithSpinner "Running update.sh..." "bash '$HOME/update.sh'" "" "Ran update.sh"; then
            logError "Failed to run update script"
            return 1
        fi
    fi

    updateProgress "Running system cleanup script" 50

    if [[ "${RUN_CLEAN:-}" == "TRUE" ]]; then
        if ! runWithSpinner "Running clean.sh..." "bash '$HOME/clean.sh'" "" "Ran clean.sh"; then
            logError "Failed to run clean script"
            return 1
        fi
    fi
}

clean() {
    remove "miscellaneous.vars"
    remove "$currentMe"

    updateProgress "Miscellaneous module tasks complete" 100
}

start
