#!/bin/bash

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

check_system_ready_system() {
   system_ready_check_help_text_cmd="'<code>sudo systemctl --wait is-system-running</code>'
(same as '<code>leaprun system-ready-check</code>')"
   check_system_ready_shared system leaprun system-ready-check
}

check_system_ready_user() {
   system_ready_check_help_text_cmd="'<code>systemctl --user --wait is-system-running</code>'"
   check_system_ready_shared user /usr/libexec/helper-scripts/system-ready-check-user
}

check_system_ready_shared() {
   local type i max leaprun_exit_code result

   type="$1"
   shift

   i="0"
   max="6"

   while true "INFO: function check_system_ready loop"; do
      leaprun_exit_code=0
      ## variable max: 6 times
      ## timeout: 5 seconds
      ## wait maximum: 6 x 5 = 30 seconds

      ## Discard output of using '&>/dev/null' so we can launch into the background
      ## and check later by looking at file '/run/helper-scripts/system-ready-check' instead.
      result="$("${@}" 2>&1)" || true
      [ -n "$result" ] || result="Empty."

      if [ "$result" = "running" ]; then
         local MSG="<p>System ready check ($type) Result: Success.</p>"
         if [ "$verbose" -ge "1" ]; then
            $output_cli ${output_opts[@]} --messagecli --typecli "info" --message "$MSG"
            $output_x ${output_opts[@]} --messagex --typex "info" --message "$MSG"
         fi
         return 0
      elif [ "$result" = "degraded" ]; then
         i="$max"
      else
         true "INFO: keep waiting."
      fi

      if [ "$i" -ge "$max" ]; then
         EXIT_CODE="1"
         local MSG="<p>System ready check ($type) Result: Failed.
<br/>
<br/>Debugging information:
<br/>Command:
<br/>$system_ready_check_help_text_cmd
<br/>result: '<code>$result</code>'</p>"
         $output_cli ${output_opts[@]} --messagecli --typecli "warning" --message "$MSG"
         $output_x ${output_opts[@]} --messagex --typex "warning" --message "$MSG"
         return 0
      fi

      (( i++ )) || true
      if [ "$i" -ge 1 ]; then
         local MSG="<p>System ready check ($type) Result: Waiting $i of $max.</p>"
         $output_cli ${output_opts[@]} --messagecli --typecli "info" --message "$MSG"
      fi
   done
}

check_system_ready() {
   check_system_ready_system
   check_system_ready_user
}
