#!/bin/bash

# SPDX-FileCopyrightText: 2024 3mdeb <contact@3mdeb.com>
#
# SPDX-License-Identifier: Apache-2.0

SBIN_DIR="/usr/sbin"

# shellcheck source=../dts-profile.sh
source "/etc/profile.d/dts-profile.sh"
export BASH_ENV="$SBIN_DIR/logging"
export TMP_LOG_DIR="/tmp/logs"
export ERR_LOG_FILE_REALPATH
export DTS_LOG_FILE
export DTS_VERBOSE_LOG_FILE
export ERR_LOG_FILE
export SHELLOPTS

mkdir -p "$TMP_LOG_DIR"
# $ERR_LOG_FILE is fd that can only be written to: '>()'. To copy logs
# we need underlying file that can be copied
ERR_LOG_FILE_REALPATH="/var/local/dts-err_$(basename "$(tty)").log"
DTS_LOG_FILE="$TMP_LOG_DIR/dts_$(basename "$(tty)").log"
DTS_VERBOSE_LOG_FILE="$TMP_LOG_DIR/dts-verbose_$(basename "$(tty)").log"

# shellcheck source=./logging.sh
source "$BASH_ENV"
start_trace_logging
start_logging
if [[ -z "$ERR_LOG_FILE" || "$ERR_LOG_FILE" == "/dev/null" ]]; then
  # pass everything written to $ERR_LOG_FILE to logger function and save it's
  # output to $ERR_LOG_FILE_REALPATH file
  exec {ERR_LOG_FILE}> >(logger >>"$ERR_LOG_FILE_REALPATH")
  ERR_LOG_FILE="/proc/$$/fd/$ERR_LOG_FILE"
fi

# shellcheck source=../include/dts-environment.sh
source $DTS_ENV
# shellcheck source=../include/dts-functions.sh
source $DTS_FUNCS
# shellcheck source=../include/hal/dts-hal.sh
source $DTS_HAL

mkdir -p "$TEMP_DIR"

# clear in case of nested dts-boot situation
export IN_FUM=
if check_if_in_fum; then
  choice="$(
    ask_for_choice "You have entered Firmware Update Mode." \
      "1" "If you wish to continue with unattended firmware update process" \
      "9" "If you wish to go back to Dasharo Tools Suite menu"
  )"
  case "$choice" in
  1) $SBIN_DIR/dasharo-deploy update fum ;;
  9) $SBIN_DIR/dts ;;
  esac
else
  $SBIN_DIR/dts
fi
