#!/bin/bash
while true
do
    data=$(sudo timeout 30s cat /dev/ttyUSB1 | tail -n 8 | grep GPRMC)
    if [[ $data == *'$GPRMC'* ]]; then
		time=$(echo "$data" | cut -d ',' -f 2)
		date=$(echo "$data" | cut -d ',' -f 10)
		hours=${time:0:2}
		minutes=${time:2:2}
		seconds=${time:4:2}
		day=${date:0:2}
		month=${date:2:2}
		year="20${date:4:2}"
		#echo "Extracted data: $data"
		#echo "Extracted date: $date"
		#echo "Extracted time: $time"
		if [ -n "$hours" ] && [ -n "$minutes" ] && [ -n "$seconds" ] && [ -n "$day" ] && [ -n "$month" ] && [ -n "$year" ]; then
			if [[ $day =~ ^[0-9][0-9]$ && $month =~ ^[0-9][0-9]$ && $year =~ ^[0-9][0-9][0-9][0-9]$ ]]; then
				new_date=$(date -u -d "$year-$month-$day $hours:$minutes:$seconds" +"%Y-%m-%d %H:%M:%S")
				current_date=$(date -u +"%Y-%m-%d %H:%M:%S")

				if [ "$new_date" != "$current_date" ]; then
					gps_timestamp=$(date -u -d "$year-$month-$day $hours:$minutes:$seconds" +"%s")
					current_timestamp=$(date -u +"%s")
					time_diff=$((gps_timestamp - current_timestamp))
					if [ $time_diff -gt 5 ] || [ $time_diff -lt -5 ]; then
						sudo date -s "$new_date"
						#echo "System date has been updated to: $new_date"
                    fi
                fi
            fi
        fi
	fi

	sleep 60
done
