#!/bin/bash

## Copyright (C) 2012 - 2020 ENCRYPTED SUPPORT LP <adrelanos@riseup.net>
## See the file COPYING for copying conditions.

#set -x
set -o pipefail
set -o errtrace

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

trap "error_handler" ERR

## root check
if [ "$(id -u)" != "0" ]; then
    echo "$0 ERROR: This must be run as root (sudo)!"
    exit 1
fi

maybe_start_anon_check() {
   anon_check_bin="whonixcheck"
   anon_check_bin_command_v_exit_code="0"
   anon_check_bin_path="$(command -v "$anon_check_bin" 2>/dev/null)" || { anon_check_bin_command_v_exit_code="$?" ; true; };

   if command -v "qubesdb-read" >/dev/null 2>&1 ; then
      qubes_extra_args="--autostart"
   fi

   if [ ! "$anon_check_bin_command_v_exit_code" = "0" ]; then
      echo "INFO: Skipping starting $anon_check_bin, because $anon_check_bin is unavailable."
      return 0
   fi
   if [ ! -x "$anon_check_bin_path" ]; then
      echo "INFO: Skipping starting $anon_check_bin, because $anon_check_bin_path is not executable."
      return 0
   fi
   echo "INFO: Starting $anon_check_bin..."
   if [ "$SUDO_USER" = "" ]; then
      sudo --non-interactive --set-home -u user "$anon_check_bin" $qubes_extra_args || { exit_code="$?" ; true; };
   else
      sudo --non-interactive --set-home -u "$SUDO_USER" "$anon_check_bin" $qubes_extra_args || { exit_code="$?" ; true; };
   fi
   echo "INFO: End of $anon_check_bin. You can always start $anon_check_bin again with:
    $anon_check_bin"
}

## This is required, otherwise whonixcheck would abort.
mkdir --parents "/var/cache/whonix-setup-wizard/status-files"
touch "/var/cache/whonix-setup-wizard/status-files/whonixsetup.done"

exit_code="0"

maybe_start_anon_check

exit "$exit_code"
