#!/usr/bin/env bash

pkg_path="/home/mepland/chance_of_showers"

# Load latest data point time

# https://stackoverflow.com/a/4561987
last_modified_csv_file=$(find $pkg_path/daq/raw_data/date_*.csv -type f -printf '%T@ %f\n' | sort -n | tail -1 | cut -f2- -d" ")

# https://stackoverflow.com/a/39847858
last_record_datetime_utc=$(tail -1 $pkg_path/daq/raw_data/"$last_modified_csv_file" | awk -F',' '{print $1}' | tr -s ' ' '||' | tr -d '"' | tr -s '||' ' ')

# Compare to current time

# https://stackoverflow.com/a/62064169
# https://stackoverflow.com/questions/10990949/convert-date-time-string-to-epoch-in-bash#comment92569832_10990961
last_record_datetime_epoch_seconds=$(date --date="$last_record_datetime_utc -0000" +"%s")
current_epoch_seconds=$(date -u +"%s")
delta_seconds="$((current_epoch_seconds - last_record_datetime_epoch_seconds))"

# Send status to healthchecks.io

chance_of_showers_heartbeat_uuid=$(jq -r '.chance_of_showers_heartbeat_uuid' $pkg_path/secrets.json)
payload="$last_modified_csv_file, $last_record_datetime_utc UTC, delta seconds = $delta_seconds"

grace_period=120
if [ "$delta_seconds" -lt "$grace_period" ]; then
	curl -fsS -m 10 --retry 5 -o /dev/null --data-raw "$payload" https://hc-ping.com/"$chance_of_showers_heartbeat_uuid"
else
	curl -fsS -m 10 --retry 5 -o /dev/null --data-raw "$payload" https://hc-ping.com/"$chance_of_showers_heartbeat_uuid"/fail
fi

# Backup data to local USB drive
backup_path="/media/usb_drive/daq_backup"
rsync -aP $pkg_path/daq/raw_data $backup_path > /dev/null 2>&1
rsync -aP $pkg_path/daq/saved_data $backup_path > /dev/null 2>&1
