#!/bin/bash

## Reached indirectly; shellcheck cannot follow the dispatch.
# shellcheck disable=SC2317

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

#set -x
set -o errexit
set -o nounset
set -o pipefail
set -o errtrace
shopt -s inherit_errexit
shopt -s shift_verbose

## The resolved PATH is captured for later use, not just a yes/no answer,
## so 'has' cannot replace this.
## style-ok: no-has

set -o pipefail
set -o errtrace

error_handler() {
   local MSG="\
###########################################################
## Something went wrong. Please report this bug!
##
## BASH_COMMAND: ${BASH_COMMAND}
###########################################################\
"
   printf '%s\n' "${MSG}"
   exit 1
}

trap "error_handler" ERR

maybe_start_systemcheck() {
   systemcheck_bin="systemcheck"
   systemcheck_bin_command_v_exit_code="0"
   gui_options=()
   systemcheck_bin_path="$(command -v "${systemcheck_bin}" 2>/dev/null)" || { systemcheck_bin_command_v_exit_code="$?" ; true; };

   ## Exported by setup-wizard-dist when it launches this, so it is absent on
   ## a direct run -- reading it bare aborts under nounset. Unset previously
   ## took the else branch, which ":-" reproduces.
   if [ "${started_by_setup_wizard_dist:-}" = "true" ]; then
      ## '--cli' optional.
      gui_options=(--gui --cli)
   else
      if ! tty --quiet ; then
         printf '%s\n' "$0: INFO: Skipping starting ${systemcheck_bin}, because started non-interactive."
         printf '%s\n' "$0: INFO: Running ${systemcheck_bin} recommended!"
         return 0
      fi
   fi

   if [ ! "${systemcheck_bin_command_v_exit_code}" = "0" ]; then
      printf '%s\n' "$0: INFO: Skipping starting ${systemcheck_bin}, because ${systemcheck_bin} is unavailable."
      return 0
   fi
   if [ ! -x "${systemcheck_bin_path}" ]; then
      printf '%s\n' "$0: INFO: Skipping starting ${systemcheck_bin}, because ${systemcheck_bin_path} is not executable."
      return 0
   fi
   printf '%s\n' "$0: INFO: Executing: ${systemcheck_bin} ${gui_options[*]}"

   exit_code="0"
   "${systemcheck_bin}" "${gui_options[@]}" || { exit_code="$?" ; true; };

   printf '%s\n' "$0: INFO: End of ${systemcheck_bin}. You can always start ${systemcheck_bin} again with:
    ${systemcheck_bin}"
}

#sudo --non-interactive /usr/libexec/setup-dist/setup-dist-done
leaprun setup-dist-done

## maybe_start_systemcheck returns early -- with "return 0" -- when
## systemcheck is unavailable, leaving exit_code unset. Default it to 0 so
## that skip path still exits successfully, as the early return intends,
## instead of aborting on the unset read.
exit_code=0

maybe_start_systemcheck

exit "${exit_code}"
