#!/usr/bin/env bash

source ./common.d/variables.sh

log()
{
    case "$2" in
        error)
            printf "\e[1m\e[31mERROR:\e[0m \e[1m%s\e[0m\n" "$1">&2;;
        internal)
            printf "\e[1m\e[96m  >>\e[0m \e[1m%s\e[0m\n" "$1">&2;;
        ierror)
            printf "\e[1m\e[31m  >>\e[0m \e[1m%s\e[0m\n" "$1">&2;;
        *)
            printf "\e[1m\e[92m>>>\e[0m \e[1m%s\e[0m\n" "$1">&2;;
    esac
}

mkdir_if_not_exists ()
{
   [ -d "$1" ] && return 0
   [ -f "$1" ] && rm -f "$1"
   mkdir "$1"
}

prepare_env()
{
    mkdir_if_not_exists "./cache"
    mkdir_if_not_exists "./out"
    mkdir_if_not_exists "./raw"
    mkdir_if_not_exists "./tmp"
}

require ()
{
    which "$1" > /dev/null 2>&1 ||
    {
        log "$1 not found" error
        exit 1
    }
}

# shellcheck disable=SC2161
# shellcheck disable=SC2086
arguments() {
    while [[ $# -gt 0 ]]; do
        opt="$1"

        shift

        case "$(echo ${opt} | tr '[:upper:]' '[:lower:]')" in
            -c | --cleanup)
                cleanup ;;

            -h | -help | --help)
                usage ;;
        
            *)
                export LNIBUILD="$opt"
                break 2 ;;
        esac
    done
}


usage() {
    log "Usage commands:"

    cat <<EOF
    # Help screen (this)
    $0 --help or $0 -h

    # Cleanup
    $0 --cleanup or $0 -c

    # Build LNIBUILD
    $0 <path/to/LNIBUILD>
EOF
    exit 0
}

# shellcheck disable=SC2162
cleanup()
{
    source ./common.d/build_functions.sh
    find ./tmp/ -mindepth 1 -maxdepth 1 | read || {
        [ -z ${quiet+x} ] && log "Nothing to clean" error
        exit 0
    }
    
    for d in ./tmp/*/; do
        log "Unmounting $d"
        detach_chroot "$d"
        umount "$d/boot/simpleinit" 2> /dev/null
        umount "$d/boot/efi" 2> /dev/null
        umount ./tmp/tmp.* 2> /dev/null
        rm -d "$d"
    done
    exit 0
}

# shellcheck disable=SC2317
_shutdown()
{
    quiet='' cleanup
    if [ -z ${1+x} ]; then
        exit 0
    else
        exit "$1"
    fi
}

sigterm_handler()
{
    sig=$?
    printf "\e[1m\e[31m>>\e[0m \e[1m%s\e[0m\n" "Shutdown signal received."
    _shutdown $sig
}

trap 'trap " " SIGINT SIGTERM SIGHUP; kill 0; wait; sigterm_handler' SIGINT SIGTERM SIGHUP