#!/bin/bash

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

## Debugging
#set -x

set -o pipefail

export PATH="$PATH:/usr/libexec/setup-dist/"

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

trap "error_handler" ERR

SCRIPTNAME="$(basename "$BASH_SOURCE")"

run_disclaimer_maybe() {
   if [ -f "/var/cache/setup-dist/status-files/disclaimer.done" ]; then
      return 0
   fi
   if [ -f "/usr/share/setup-dist/status-files/disclaimer.skip" ]; then
      return 0
   fi
   if [ -f "/var/cache/whonix-setup-wizard/status-files/disclaimer.done" ]; then
      return 0
   fi
   if [ -f "/usr/share/whonix-setup-wizard/status-files/disclaimer.skip" ]; then
      return 0
   fi

   ## Disable disclaimer.
   return 0

   exit_code="0"
   ft_disclaimer || { exit_code="$?" ; true; };

   if [ ! "$exit_code" = "0" ]; then
      echo "You can always enter setup-dist again, by starting: setup-dist"
      exit 0
   fi

   mkdir --parents "/var/cache/setup-dist/status-files"
   touch "/var/cache/setup-dist/status-files/disclaimer.done"
}

check_passwords() {
   local output
   output="$(leaprun get-password-status-list)"
   if printf "%s" "$output" | grep --quiet --ignore-case -- 'Absent'; then
      printf '%b\n' "[${yellow}NOTICE${nocolor}] Some user accounts on this system are passwordless. Run 'systemcheck' for more information."
   fi
}

start_systemcheck() {
   TITLE="setup-dist - Success!"
   MSG="
Press Enter to run systemcheck and exit.
"
   dialog_wrapper --title "$TITLE" --msgbox "$MSG" 640 480
   ## Start systemcheck.
   exit_code="0"
   ft_m_end || { exit_code="$?" ; true; };
}

if [ "$(id -u)" = "0" ]; then
    echo "ERROR: This must NOT be run as root (sudo)!"
    echo "INFO: You can start $SCRIPTNAME by entering..."
    echo "      $SCRIPTNAME"
    exit 1
fi

source "/usr/libexec/setup-dist/shared"
source "/usr/libexec/helper-scripts/get_colors.sh"

command -v dialog >/dev/null
command -v dialog_wrapper >/dev/null

run_disclaimer_maybe
check_passwords

if [ -f "/usr/share/anon-ws-base-files/workstation" ]; then
   start_systemcheck
elif [ -f "/usr/share/anon-gw-base-files/gateway" ]; then
   start_systemcheck
fi
