#!/bin/bash -e

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

set -x

output_cmd() {
   local msg="$@"
   echo "$msg"
   echo "$msg" | systemd-cat --identifier="qvm-sync-clock.anondist" || true
}

output_cmd "$0: START"
output_cmd "whoami: $(whoami)"

# if [ ! -f /run/qubes/this-is-templatevm ]; then
#    ## dom0 should not tell us its time.
#    ## But if it does, create a file, so systemcheck could warn in case this
#    ## file exists.
#    read timestamp
#    mkdir -p "/run/qubes-whonix"
#    echo "$timestamp" > "/run/qubes-whonix/qubes.SetDateTime"
#    exit 0
# fi

## Running in Template, ok.

## Workaround for a Qubes bug.
## https://github.com/Whonix/updates-status/issues/1
randomized_unix_time="$(timeout --kill-after="5" "5" /usr/lib/qubes/qrexec-client-vm dom0 qubes.GetRandomizedTime)" || \
   output_cmd "ERROR - /usr/lib/qubes/qrexec-client-vm had non-zero exit code."

if [[ "$randomized_unix_time" =~ ^[+-]?[0-9]+\.?[0-9]*$ ]]; then
   output_cmd "INFO - date before roughly fixing it: $(date --utc)"
   date --utc --set "@$randomized_unix_time" >/dev/null
   output_cmd "INFO - date after roughly fixing it : $(date --utc)"
else
   output_cmd "ERROR - randomized_unix_time: '$randomized_unix_time'"
fi

output_cmd "$0: END"
