#!/bin/bash

#set -x

true "$0: START"

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

set -o errexit
set -o nounset
set -o errtrace
set -o pipefail

## For future use in case of issues.
## Building dist-installer-cli is not crucial and a workaround to skip it might unbreak the build process.
## https://forums.whonix.org/t/derivative-maker-missing-usr-libexec-helper-scripts-get-colors-sh/20142
if [ "${dist_build_skip_installer_dist_standalone:-}" = "true" ]; then
  echo "$0: INFO: Skipping to build dist-installer-cli because dist_build_skip_installer_dist_standalone=true, ok."
  exit 0
fi

command -v git >/dev/null || exit 1

toplevel="$(git rev-parse --show-toplevel)"
target="${toplevel}/usr/share/usability-misc/dist-installer-cli-standalone"
template="${toplevel}/usr/bin/dist-installer-cli"

## debian/control 'Builds-Depends: helper-scripts' is not easily possible,
## because then the build chroot would also need helper-scripts being installed.
# if test -d /usr/libexec/helper-scripts/ ; then
#   ## System version.
#   ## Stable. Or not. Depending on repository setting stable, stable-proposed-updates, testers, or developers.
#   helper_path="/usr/libexec/helper-scripts/"
# elif test -d "../helper-scripts/usr/libexec/helper-scripts/" ; then
#   ## derivative-maker source code version.
#   helper_path="../helper-scripts/usr/libexec/helper-scripts/"
# else
#   echo "$0: ERROR: helper_path neither available in
# - /usr/libexec/helper-scripts/
# nor in
# ../helper-scripts/usr/libexec/helper-scripts/" >&2
#   exit 1
# fi

## Use source code version for now to avoid using different version depending on repository setting.
## TODO: does not work
#helper_path="../helper-scripts/usr/libexec/helper-scripts/"

helper_path="/usr/libexec/helper-scripts/"

if ! test -d "$helper_path" ; then
  echo "$0: ERROR: directory helper_path '$helper_path' does not exist!" >&2
fi

cp -- "${template}" "${target}"

awk -v origin="${0##*/}" -v helper="source ${helper_path}" '
  $0 ~ helper {
    if (system("test -f "$2) != 0) {
      print origin ": error: sourced file does not exist: "$2 > "/dev/stderr"
      exit 1
    }
    print "##### BEGIN pasted by "origin " from file "$2
    system("cat "$2)
    print "##### END pasted by "origin " from file "$2
    next
  }
  1
' "${template}" | tee -- "${target}" >/dev/null

sed -i \
  -e "\,^\s*source /usr/libexec/helper-scripts/,d" \
  -e "3i ## DO NOT MODIFY, AUTOGENERATED CODE, MODIFY ../../bin/dist-installer-cli and the functions sourced" \
  "${target}"

echo "$0: INFO: BUILD: SUCCESS"
echo "$0: INFO: Running shellcheck..."

shellcheck "${target}"

echo "$0: INFO: shellcheck: SUCCESS"
echo "$0: INFO: END: OK"
