#!/bin/bash
# Command-line world clock by PPC 10/1/2022, GPL license
#Adapted from https://gist.github.com/rangersmyth74/4c7e291b64d48c1beb7029e9b07b6bca
#and from examples over at stackoverflow like over at https://stackoverflow.com/questions/370075/command-line-world-clock

# create preference file $HOME/.world-clock.zones, if it's missing
if [ ! -f $HOME/.world-clock.zones ]; then
echo "Europe/London
Europe/Paris
Asia/Tokyo
America/St_Johns
Brazil/West" > $HOME/.world-clock.zones
fi

worldtz () {
	: ${WORLDCLOCK_ZONES:=$HOME/.world-clock.zones}
: ${WORLDCLOCK_FORMAT:='+%Y-%m-%d %H:%M:%S %Z'}
echo
echo "		CLI World Clock:"
echo
local_time=$(date "$WORLDCLOCK_FORMAT")
echo "Local Time	       $local_time"
echo
while read zone
do echo $zone '!' $(TZ=$zone date "$WORLDCLOCK_FORMAT")

done < $WORLDCLOCK_ZONES |
awk -F '!' '{ printf "%-20s  %s\n", $1, $2;}' |
sort -b -r -k2,2 -k3,3
echo
echo "To manage the time zones, edit the file $HOME/.world-clock.zones"
echo "All time zones are listed at https://en.wikipedia.org/wiki/List_of_tz_database_time_zones"
echo
echo "Press any key to exit"
}

export -f worldtz
watch -t -n 1 -x bash -c worldtz  &   # put function in the background
read -n 1
kill $!               # kill the the job most recently placed into the background
read -t 0.1 -n 1000000
