#!/bin/bash

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

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

source /usr/libexec/helper-scripts/systemd-notify.bsh

target_vm="$(/usr/libexec/sdwdate-gui/sdwdate-gui-config-read 'gateway')" || exit 1

connect_check_counter=0
connect_check_rslt='n'
while (( connect_check_counter < 10 )); do
  sleep 1
  (( connect_check_counter += 1 )) || true
  connect_check_rslt="$(
    ## We redirect a blank string into this qrexec-client-vm invocation's
    ## stdin, because otherwise it will eat the script's stdin up to this
    ## point, preventing some data from reaching the server.
    qrexec-client-vm "${target_vm}" sdwdate-gui.ConnectCheck <<< "" 2>&1
  )" || connect_check_rslt='n'
  if [ "${connect_check_rslt}" = 'n' ]; then
    continue
  fi
  break
done

if [ "${connect_check_rslt}" != 'y' ]; then
  ## Not exiting 1 here, since this service is expected to fail if the
  ## sdwdate-gui-server VM is not running. The client will continue retrying
  ## until the sdwdate-gui-server VM is started regardless of the exit code
  ## here.
  exit 0
fi

"${systemd_notify[@]}" --ready

exec qrexec-client-vm "${target_vm}" sdwdate-gui.Connect
