#!
#
#	RTC(DS1302) and Raspbian clock synchronization script
#		(c) 2019	1YEN Toru
#
#
#	2019/09/14	ver.1.00
#
@ rpi2rtc = 0							# clock sync. Raspbian to RTC
@ rtc2rpi = 0							# clock sync. RTC to Raspbian
#
echo -n "1302:	"
rtc_ds1302
if ( $status == 0 )\
	@ rtc2rpi ++
#
echo -n "DATE:	"
date +'%Y-%m-%d %H:%M:%S'
if ( `timedatectl show | grep 'NTPSynchronized=yes' | wc -l` == 1 )\
	@ rpi2rtc ++
#
echo "--------"
if ( $rpi2rtc > 0 ) then
	if ( $rtc2rpi > 0 ) then
		# clock sync Raspbian --> RTC
		echo "clock sync Raspbian --> RTC"
		rtc_ds1302 -set "`date +'%Y-%m-%d %H:%M:%S'`"
	else
		# ERROR:
		echo "ERROR: RTC was not available."
		exit 255
	endif
else if ( $rtc2rpi > 0 ) then
	# clock sync RTC --> Raspbian
	echo "clock sync RTC --> Raspbian"
	sudo date -s "`rtc_ds1302`"
else
	# ERROR:
	echo "ERROR: NTP and RTC were not available."
	exit 255
endif
echo "--------"
#
echo -n "1302:	"
rtc_ds1302
echo -n "DATE:	"
date +'%Y-%m-%d %H:%M:%S'
