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

set -euo pipefail

currentName="Utilities Installer"
currentVersion="0.12"
currentMe=$(basename "$0")

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

parentModule="${1:-}"

start() {
    source "utils.sh"

    trap clean ERR

    initProgress "Utilities" "$parentModule"
    logInfo "$currentName v$currentVersion"
    prepare
    execute
    clean
}

prepare() {
    updateProgress "Preparing Utilities module" 5

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

    source "utilities.vars"
}

execute() {
    updateProgress "Ensuring Mail recipient in crontab" 20

    ensureMailto

    if [[ "${UPDATE_SCRIPT:-}" ]]; then
        updateProgress "Installing Update script" 35

        if ! download "$UPDATE_SCRIPT" "update.sh" "${skipChecksum:-}"; then
            logError "Failed to download update script from $UPDATE_SCRIPT"
            return 1
        fi

        chmod +x "update.sh"
        if ! move "update.sh" "$HOME/update.sh"; then
            logError "Failed to move update.sh to $HOME/"
            return 1
        fi

        if [[ "${UPDATE_CRON:-}" ]]; then
            if ! addCronjob "$UPDATE_CRON bash $HOME/update.sh"; then
                logError "Failed to add update cron job"
                return 1
            fi
        fi
    fi

    if [[ "${CLEAN_SCRIPT:-}" ]]; then
        updateProgress "Installing Clean script" 60

        if ! download "$CLEAN_SCRIPT" "clean.sh" "${skipChecksum:-}"; then
            logError "Failed to download clean script from $CLEAN_SCRIPT"
            return 1
        fi

        chmod +x "clean.sh"
        if ! move "clean.sh" "$HOME/clean.sh"; then
            logError "Failed to move clean.sh to $HOME/"
            return 1
        fi

        if [[ "${CLEAN_CRON:-}" ]]; then
            if ! addCronjob "$CLEAN_CRON bash $HOME/clean.sh"; then
                logError "Failed to add clean cron job"
                return 1
            fi
        fi
    fi
}

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

    updateProgress "Utilities module configuration complete" 100
}

start
