##!/bin/bash

# This script is intented to save current system time to file periodically.
# It is then read at next re-boot stage to set system time.

# To make sure that the file systemTime.txt stays valid even after power cycle, it is written first into the temporary file.
# Then its copy is made, and then that copy file is flushed to the disk from buffer by fsync command, to make sure it is written in full.

fileName=/opt/thingworx/systemTime.txt
fileNameTmp=/opt/thingworx/systemTimeTmp.txt

# Get currnet year.	
# If current year is greater than 2018, then most likely it is set correctly, and current time can be stored in file.

if ! [ -f /var/lock/prosoft-save-time-running ]; then
	touch /var/lock/prosoft-save-time-running
	echo "Starting script to save current time periodically to file $fileName" 
	until [ ]
	do 
		current_year=$(date +'%Y')
		if [ "$current_year" -gt "2018" ]; then
			rm -f $fileNameTmp
			date -I'seconds' > $fileNameTmp
			sed -i 's/T/ /g' $fileNameTmp
			sed -i 's/+0000//g' $fileNameTmp
			cp -f $fileNameTmp $fileName
			sync $fileName
		else
			rm -f $fileName
		fi
		sleep 30
	done
fi