#!/bin/bash

## Copyright (C) 2012 - 2023 ENCRYPTED SUPPORT LP <adrelanos@whonix.org>
## See the file COPYING for copying conditions.

set -x
set -e

true "INFO: Currently running script: $BASH_SOURCE $@"

MYDIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

cd "$MYDIR"

source ./help-steps/pre
source ./help-steps/colors

error_handler_dist_build_one() {
   true "${red}${bold}ERROR in $0${reset}"
   true "${red}${bold}BASH_COMMAND${reset}: $BASH_COMMAND"
   true "${red}${bold}dist_build_one_build_step_current${reset}: $dist_build_one_build_step_current"
   true "${red}\$@: $@${reset}"
   true "${red}${bold}INFO: Now exiting from $0 (because error was detected, see above).${reset}"
   exit 1
}

trap "error_handler_dist_build_one" ERR

dist_build_machine() {
   run-parts --verbose --test ./build-steps.d

   ## Not using:
   #run-parts --verbose --exit-on-error ./build-steps.d
   ## Because of an issue,
   ## "run-parts, trap INT, read error":
   ## https://lists.gnu.org/archive/html/help-bash/2015-03/msg00066.html

   for dist_build_one_build_step_current in ./build-steps.d/*; do
      if [ -x "$dist_build_one_build_step_current" ]; then
         ## If the last character is a ~, ignore that file,
         ## because it was created by some editor,
         ## which creates backup files.
         if [ "${dist_build_one_build_step_current: -1}" = "~" ]; then
            continue
         fi
         ## Skipping files such as .dpkg-old and .dpkg-dist.
         if ( echo "$dist_build_one_build_step_current" | grep -q ".dpkg-" ); then
            true "skip $dist_build_one_build_step_current"
            continue
         fi
         true "${cyan}${bold}${under}############################################################${reset}"
         true "${cyan}${bold}${under}############################################################${reset}"
         true "${cyan}${bold}${under}############################################################${reset}"
         true "${cyan}${bold}${under}INFO: BEGIN: dist_build_one_build_step_current: $dist_build_one_build_step_current${reset}"
         "./$dist_build_one_build_step_current" "$@"
         true "${cyan}${bold}${under}INFO: END  : dist_build_one_build_step_current: $dist_build_one_build_step_current${reset}"
         true "${cyan}${bold}${under}############################################################${reset}"
         true "${cyan}${bold}${under}############################################################${reset}"
         true "${cyan}${bold}${under}############################################################${reset}"
      fi
   done
}

main() {
   if [ "$1" = "--help" ]; then
      ./help-steps/parse-cmd --help
      exit 0
   fi

   root_check

   ## XXX
   trap "error_handler_dist_build_one" ERR
   trap - INT
   trap - TERM

   dist_build_machine "$@"

   true
}

main "$@"
