#!/usr/bin/env bash

set -eu

# ----------------------------------------------------------------------------------------------------------------------
# Include this script to create $OUTPUT_REDIRECT and automatically show logs on error.
# You must create $OUTPUT_REDIRECT_PATH and $OUTPUT_REDIRECT_PATHNAME before including this script.
# You can include verbosity.inc.bash before this script to create $VERBOSITY_LEVEL or create it by yourself.
# ----------------------------------------------------------------------------------------------------------------------

function onError() {
    if [ -f "${OUTPUT_REDIRECT_PATHNAME}" ]; then
        cat "${OUTPUT_REDIRECT_PATHNAME}"
    fi

    printf "\e[0;31mError at line ${1}.\e[0m\n"
}

function rmOutputRedirectContent() {
    if [ -f "${OUTPUT_REDIRECT_PATHNAME}" ]; then
        rm "${OUTPUT_REDIRECT_PATHNAME}"
    fi
}

trap 'onError ${LINENO}' ERR

readonly OUTPUT_REDIRECT="${OUTPUT_REDIRECT_PATHNAME}"
if [ ! -d "${OUTPUT_REDIRECT_PATH}" ]; then
    mkdir -p "${OUTPUT_REDIRECT_PATH}"
fi


rmOutputRedirectContent
