#!/bin/bash

# "One way or another, we are going to set the system clock!"
#
# This script was created by the SARPi Project for setting the system clock
# at boot time prior to Slackware Linux installation. It assumes that a file
# is present in the root of the initrd which contains a Unix timestamp of the
# image build date: /.installer_build_date
#
# Exaga - sarpi.penthux.net - 20 Feb 2024
#
######

# Get installer build Unix timestamp
INSTALLER_BUILD_TIMESTAMP="$(cat /.installer_build_date)"

# Check for online connectivity
nc -z -w 6 8.8.8.8 53 &> /dev/null
ONLINE=$?

# If online...
if [ $ONLINE -eq 0 ]; then
  # set system clock from ntp server [remote]
  /usr/sbin/ntpdate time.google.com &> /dev/null || \
  /usr/sbin/ntpdate 0.pool.ntp.org &> /dev/null
  # set RTC [if one is found]
  [ -h /dev/rtc ] && /sbin/hwclock --systohc &> /dev/null 
# If not online use onboard RTC [if one is found]
elif [ -h "/dev/rtc" ]; then
  /sbin/hwclock --hctosys &> /dev/null
# Otherwise use installer build Unix timestamp
elif [ "$(date +'%s')" -le "${INSTALLER_BUILD_TIMESTAMP}" ]; then
  date -s "@${INSTALLER_BUILD_TIMESTAMP}" &> /dev/null
# Or use -24hr Unix timestamp as a last resort
else
  date -s yesterday &> /dev/null
fi

# Done
exit

