#!/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

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_ret=0
  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.ConnectCheck <<< ""
  )" || connect_check_ret="$?"
  if [ "${connect_check_ret}" != '0' ] \
    || [ "${connect_check_rslt}" = 'n' ]; then
    continue
  fi
  break
done

if [ "${connect_check_rslt}" != 'y' ]; then
  exit 1
fi

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