#!/bin/bash

# Author: Marcos Tischer Vallim. <https://github.com/mvallim>
# Author: crims0n. <https://minios.dev>

set -e          # exit on error
set -o pipefail # exit on pipeline error
set -u          # treat unset variable as error

SET_E=""
SET_U=""

# ---[ CONSTANTS & VARIABLES ]---
SCRIPT_DIR="$(dirname "$(readlink -f "${0}")")"
: "${MAIN_EXECUTABLE:="minios-live"}"
: "${BUILD_SCRIPTS:="linux-live"}"
: "${RELEASE_VERSION:=""}"
: "${RELEASE:="false"}"
[ -n "${RELEASE_VERSION}" ] && RELEASE="true"

if [[ "$SCRIPT_DIR" == "/usr/bin" ]]; then
    BUILD_SCRIPTS_DIR="/usr/share/minios-live"
    : "${BUILD_CONF:="/etc/minios-live/build.conf"}"
    : "${BUILD_DIR:="$PWD/build"}"
else
    BUILD_SCRIPTS_DIR="$SCRIPT_DIR/$BUILD_SCRIPTS"
    : "${BUILD_CONF:="$BUILD_SCRIPTS_DIR/build.conf"}"
    : "${BUILD_DIR:="$SCRIPT_DIR/build"}"
fi
export DEBIAN_FRONTEND=noninteractive

MINIOSLIB="${BUILD_SCRIPTS_DIR}/minioslib"

# ---[ SOURCE FILES ]---
. "$MINIOSLIB" || exit 1

console_colors

# ---[ INITIALIZE BUILD DIRECTORY & CONFIGURATION ]---
if [[ "$MAIN_EXECUTABLE" = "minios-cmd" && ! -f "$BUILD_CONF" ]]; then
    if [[ "$SCRIPT_DIR" == "/usr/bin" ]]; then
        cp "/etc/minios-live/build.conf" "$BUILD_CONF"
    else
        cp "$SCRIPT_DIR/$BUILD_SCRIPTS/build.conf" "$BUILD_CONF"
    fi
fi

. "$BUILD_CONF" || exit 1
export VERBOSITY_LEVEL

[ "${VERBOSITY_LEVEL}" -ge 2 ] && export PS4='+ ${BASH_SOURCE}:${LINENO}: ' && set -x

# ---[ FUNCTIONS ]---
help() {
    local HEADLINE="${1:-$(gettext 'This script builds bootable MiniOS ISO image.')}"
    # show hyphenated command names
    local COMMANDS="${CMD[*]//_/-}"
    local SYNTAX="$0 [start_cmd] [-] [end_cmd]"
    local EXAMPLES=(
        "${LIGHTYELLOW}  $0 -                              ${ENDCOLOR}$(gettext "Run the build from start to finish.")"
        "${LIGHTYELLOW}  $0 build-bootstrap - build-chroot ${ENDCOLOR}$(gettext "Start the build by building the base environment and finish by installing the entire system in chroot.")"
        "${LIGHTYELLOW}  $0 - build-chroot                 ${ENDCOLOR}$(gettext "Start the build from the beginning and finish by installing the entire system in chroot.")"
        "${LIGHTYELLOW}  $0 build-bootstrap -              ${ENDCOLOR}$(gettext "Start the build by building the base environment and run to completion.")"
        "${LIGHTYELLOW}  $0 build-iso                      ${ENDCOLOR}$(gettext "Build only ISO image from previously prepared data.")"
    )

    echo -e "${LIGHTYELLOW}${HEADLINE}${ENDCOLOR}\n"
    echo -e "$(gettext "Supported commands:") ${CYAN}${COMMANDS}${ENDCOLOR}\n"
    echo -e "$(gettext "Usage:") ${MAGENTA}${SYNTAX}${ENDCOLOR}"
    echo -e "$(gettext "  Run from start_cmd to end_cmd")"
    echo -e "$(gettext "  If start_cmd is omitted, start from the first command")"
    echo -e "$(gettext "  If end_cmd is omitted, end with the last command")"
    echo -e "$(gettext "  Enter a single cmd to run the specific command")"
    echo -e "$(gettext "  Enter '-' as the only argument to run all commands\n")"
    echo -e "$(gettext "Examples:")"
    for EXAMPLE in "${EXAMPLES[@]}"; do
        echo -e "${EXAMPLE}"
    done

    exit 0
}

# ---[ BUILD PATHS AND DIRECTORIES ]---
APTCACHE_DIR="$BUILD_DIR/aptcache/$DISTRIBUTION"
ROOTFS_TARBALL="$BUILD_DIR/rootfs/$DISTRIBUTION-$DISTRIBUTION_ARCH-rootfs.tar.gz"
ISO_DIR="$BUILD_DIR/iso"
WORK_DIR="$BUILD_DIR/$DISTRIBUTION-$PACKAGE_VARIANT-$DISTRIBUTION_ARCH"
INSTALL_DIR="$WORK_DIR/core"
EXCLUDE_CORE_FILE="$WORK_DIR/squashfs-core-exclude"

# ---[ COMMANDS ]---
CMD=(build_bootstrap build_chroot build_live build_modules build_boot build_config build_iso remove_sources)

# ----[ MAIN ]----
create_log_file "$@"

# normalize both hyphens and underscores into underscore form,
# but leave lone "-" untouched
ARGS=("$@")
for idx in "${!ARGS[@]}"; do
    [[ "${ARGS[$idx]}" == "-" ]] && continue
    ARGS[$idx]="${ARGS[$idx]//-/_}"
done
set -- "${ARGS[@]}"

#trap 'mountpoint -q "$WORK_DIR" && unmount_dirs "$WORK_DIR"' EXIT
trap 'mountpoint -q "$WORK_DIR" && unmount_dirs "$WORK_DIR"; [ "${USE_APT_CACHE_REPO}" = "true" ] && stop_http_server' EXIT

common_variables

allow_root_only

if [[ " ${CMD[@]:-} " =~ " ${1:-} " ]] || [[ "${1:-}" == "-" ]]; then
    if [ "${USE_APT_CACHE_REPO}" = "false" ]; then
        toggle_shell_options e
        check_internet_connection
        toggle_shell_options e
    fi

    [[ "${CONTAINER,,}" == "true" ]] && new_run

    mkdir -p "${INSTALL_DIR}"

    generate_chroot_configuration_file "$WORK_DIR/minios_build.conf"

    ensure_host_prerequisites

    #generate_squashfs_exclude_file "${EXCLUDE_CORE_FILE}" "${INSTALL_DIR}"

fi

determine_command_range "$@"

# Run commands within the defined range.
for ((ii = START_INDEX; ii < END_INDEX; ii++)); do
    "${CMD[ii]}"
done

echo -e "${BOLD}${LIGHTYELLOW}$0${ENDCOLOR} - ${LIGHTGREEN}Command completed successfully!${ENDCOLOR}"
