#!/bin/bash

FALLBACK_TS=1583855743
TS="$(curl -k -f -sS https://cloud.3dprinteros.com/noauth/get_timestamp)"
TS=$((TS))
if [ $TS -le $FALLBACK_TS ]; then
  TS=$FALLBACK_TS
  echo "Some error on reading timestamp from 3DPrinterOS Cloud. Using fallback timestamp ($TS)"
fi
CURTS="$(date +%s)"
if [ $((TS-60)) -gt $((CURTS)) ] || [ $((TS+3600)) -lt $((CURTS)) ]; then
  echo "Wrong system timestamp ($((CURTS))). Adjusting using 3DPrinterOS Cloud ($TS)"
else
  echo "System timestamp seems to be correct. Timestamp adjusting was skipped"
  exit 0
fi

date --set="@$TS"
hwclock --systohc
