#!/bin/bash

# Save bash history (and optionally echo it out as it happens)
# This is defined here, but the trap is only enabled in the `build_script.sh` that is generated by `BuildConfig`.
# This avoids annoyances like this trap being enabled during debug shells, etc....
function save_history() {
	# When a command fails, we enter the `ERR` trap, which starts to run statements, but we want to
	# ignore those, so we explicitly catch it here, and then disable ourselves.
	if [[ "$?" != "0" ]]; then
		trap - DEBUG
		return
	fi
    # Skip special commands
    if [[ "${BASH_COMMAND}" == trap* ]] || [[ "${BASH_COMMAND}" == false ]] || [[ "${BASH_COMMAND}" == *command-not-found* ]]; then
        return
    fi
	if [[ "${BB_PRINT_COMMANDS}" == "true" ]]; then
		echo " ---> ${BASH_COMMAND}" >&2
	fi
    history -s "${BASH_COMMAND}"
    history -a
}

# Save our environment into `/workspace/metadir/env`, eliminating read-only variables
# so that this file can be sourced upon entering a debug shell.
function save_env() {
	set +x
	# Ignore read-only variables
	GREP_CMD="^GREP_CMD="
	for GREP_VAR_NAME in BASH_ARGC BASH_ARGV BASH_CMDS BASH_COMMAND BASH_LINENO BASH_SOURCE BASHOPTS BASH_VERSINFO UID EUID PPID SHELLOPTS POSIXLY_CORRECT GREP_VAR_NAME _; do
		GREP_CMD="${GREP_CMD}|^${GREP_VAR_NAME}="
	done
	set -o posix; set | grep -E -v "${GREP_CMD}" > /workspace/metadir/env; set +o posix
	echo "cd $(pwd)" >> /workspace/metadir/env
}

if [ -f /workspace/metadir/env ]; then
	source /workspace/metadir/env
fi

function on_error_trap() {
	RET="$?"
	# Disable any further traps here
	trap - TERM EXIT
	set +e +x
	if [[ "${RET}" != 0 ]]; then \
		echo "Previous command '${BASH_COMMAND}' exited with code ${RET}" >&2; \
	fi
	if [[ "${BB_SAVE_ENV:-true}" == "true" ]]; then
		save_env
	fi
	exit "${RET}"
}

# On any kind of exit, save our environment out to our metadir
trap on_error_trap TERM EXIT
