#!/bin/bash

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

set -e

time_sanity_check() {
   ## with:
   ## Sun Jan 17 03:20:53 UTC 2021
   ## without:
   ## Sun 17 Jan 2021 03:21:02 AM UTC
   export LC_TIME=C
   ## Just in case.
   export TZ=UTC

   ## Expiration date in unixtime.
   ## date --utc --date '17 MAY 2033 10:00:00' '+%s'
   ## 1999936800
   EXPIRATION_UNIXTIME="1999936800"
   ## Convert seconds since the epoch (1970-01-01 UTC) (unixtime) to a date
   ## date --utc --date="@1999936800"

   MINIMUM_UNIXTIME="$(cat "/usr/share/timesanitycheck/minimum_unixtime")"
   MINIMUM_HUMAN_READABLE_TIME="$(date --utc --date "@$MINIMUM_UNIXTIME")"

   ## time after boot
   BOOT_UNIXTIME="$(date --utc "+%s")"
   BOOT_HUMAN_READABLE_TIME="$(date --utc)"

   ## expiration date
   ## EXPIRATION_UNIXTIME variable gets sourced from /etc/default/$NAME
   EXPIRATION_HUMAN_READABLE_TIME="$(date --utc --date="@${EXPIRATION_UNIXTIME}")"

   ## time_sanity_check_msg_dynamic is used by /usr/share/timesanitycheck/start.
   ## time_sanity_check_msg_static is used by /usr/libexec/helper-scripts/onion-time-pre-script.

   if [ "$BOOT_UNIXTIME" -lt "$MINIMUM_UNIXTIME" ]; then
      time_sanity_check_msg_dynamic="The clock is slow.
       (Current time '$BOOT_HUMAN_READABLE_TIME' ('$BOOT_UNIXTIME') is less than
 the minimum time '$MINIMUM_HUMAN_READABLE_TIME' ('$BOOT_UNIXTIME').)"
       time_sanity_check_msg_static="The clock is slow.
(Current time is less than the minimum time '$MINIMUM_HUMAN_READABLE_TIME'.)"
      time_sanity_check_exit_code=2
      return
   fi

   if [ "$BOOT_UNIXTIME" -gt "${EXPIRATION_UNIXTIME}" ]; then
      time_sanity_check_msg_dynamic="The clock is fast.
       (Current time '$BOOT_HUMAN_READABLE_TIME' ('$BOOT_UNIXTIME') is greater than
 the minimum time '$EXPIRATION_HUMAN_READABLE_TIME' ('${EXPIRATION_UNIXTIME}').)"
      time_sanity_check_msg_static="The clock is fast.
Current time is greater than the expiration timestamp '$EXPIRATION_HUMAN_READABLE_TIME'."
      time_sanity_check_exit_code=3
      return
   fi

   time_sanity_check_msg_dynamic="Current time '$BOOT_HUMAN_READABLE_TIME' ('$BOOT_UNIXTIME')."
   time_sanity_check_msg_static="Within minimum time '$MINIMUM_HUMAN_READABLE_TIME' and expiration timestamp '$EXPIRATION_HUMAN_READABLE_TIME', ok."
   time_sanity_check_exit_code=0
}

time_sanity_check

echo "$time_sanity_check_msg_static"

exit $time_sanity_check_exit_code
