#!/bin/bash

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

set -e

source /usr/share/bootclockrandomization/shared

do_start () {
   log "Boot Clock Randomization"
   log "https://www.kicksecure.com/wiki/Boot_Clock_Randomization"

   if [ -e "$FAIL_FILE" ]; then
      rm -f "$FAIL_FILE"
   fi
   if [ -e "$SUCCESS_FILE" ]; then
      rm -f "$SUCCESS_FILE"
   fi

   ## Lower in Qubes Template.
   ## Because sdwdate (or other time fixing mechanism) does not yet run in Template.
   ## https://forums.whonix.org/t/whonix-ws-16-template-fails-to-update-due-to-timing-issue/12739/31
   if test -f /run/qubes/this-is-templatevm ; then
      : ${delay_plus_or_minus:="1"}
   fi
   : ${delay_plus_or_minus:="180"}

   get_random_time

   ## Set new time. Syntax: date --set @1396733199.112834496
   date --set "@$NEW_TIME.$NANOSECONDS" > /dev/null

   ## Testing the `date` syntax:
   ## sudo date --set @1396733199.112834496 ; date +%s.%N
   ## Sat Apr  5 21:26:39 UTC 2014
   ## 1396733199.114119019
   ## sudo date --set @1396733199.112834496 ; date +%s.%N
   ## Sat Apr  5 21:26:39 UTC 2014
   ## 1396733199.114122807

   log "Changed time from $OLD_TIME ($OLD_TIME_NANOSECONDS)"
   log "               to $(date) ($(date +%s.%N))."

   touch "$SUCCESS_FILE"
   return 0
}

do_start
