#!/bin/sh

me="[$(basename ${0})]"

printf "${me} Enter.\\n"

# Load ipmodule variables
. /opt/gira/share/devicestack/ipmodule-vars
. /opt/gira/share/devicestack/ipmodule-functions

case "${1}" in
  start)
  #
  # Check the date of some files to determine, if the system time is too old - in case of a long power off - and set it to a defined "younger" time.
  #

  check_time() {
    now_t=$(date +"%s")
    if [ -f "$1" ]; then
      test_t=$(date +"%s" -r "$1")
      if [ "$now_t" -lt "$test_t" ]; then
        log ${me} "Timestamp of '$1' is newer than current system time. Setting new system time ($(date -r "$1"))."
        date --set="@$test_t"
        exit
      fi
    else
      log ${me} "Could not find '$1' for a timestamp check."
    fi
  }

  touch_timetag_hourly() {
    while true
    do
      sleep 3600
      touch /opt/userdata/.timetag
    done
  }

  # start the touch script to have the most recent fallback time very hour
  touch_timetag_hourly &
  echo $! > /var/run/check_and_set_clock.pid

  # check time in the following prority
  check_time /opt/userdata/.timetag
  check_time /opt/userdata/gpaproject/activedir
  check_time /opt/extparam/ssl_cert

  # nothing to be done
  log ${me} "Startup system time seems to be okay."
  ;;
  stop)
  if [ -f /var/run/check_and_set_clock.pid ]; then
    kill -9 $(cat /var/run/check_and_set_clock.pid)
    rm -f /var/run/check_and_set_clock.pid
  fi
  ;;
  *)
    printf "Usage: %s (start|stop)\\n" "$0"
    exit 1
esac

printf "${me} Exit.\\n"

exit 0
