#!/bin/sh
# tmdconv.sh --- tiny menu-based date converter

# Copyright (c) 2024 Amin Bandali <[email protected]>
#
# Copying and distribution of this file, with or without modification,
# are permitted in any medium without royalty provided the copyright
# notice and this notice are preserved.  This file is offered as-is,
# without any warranty.

# https://kelar.org/~bandali/software/tmdconv/
# gopher://kelar.org/1/~bandali/software/tmdconv/
# gopher://zaibatsu.circumlunar.space/1/~bandali/software/tmdconv/
# gemini://zaibatsu.circumlunar.space/~bandali/software/tmdconv/


tzdata="${tzdata:-/usr/share/zoneinfo/tzdata.zi}"

usage()
{
   cat <<EOF
Usage: $0 [OPTIONS]

The following OPTIONS are accepted:
-g  run in graphical user interface mode
-l  display longer output
-h  print help and exit
EOF
   exit "$1"
}

ask()
{
   # $1: newline-separated choices
   # $2: prompt string
   # $3: pre-filled initial answer (if supported)

   if [ "$gui" ]; then
       if [ "$WAYLAND_DISPLAY" ]; then
           menu_font='Source Code Pro Medium 10.5'
           printf "$1" | wmenu -i -p "$2" -f "$menu_font"
       else
           menu_font='Source Code Pro Medium-10.5'
           printf "$1" | dmenu -i -p "$2" -fn "$menu_font"
       fi
   else
       printf "$1" \
           | fzf --print-query --prompt="$2" --query="$3" \
           | tail -n -1
   fi
}

say()
{
   if [ "$gui" ]; then
       notify-send "$1"
   else
       printf "$1\n"
   fi
}

systemtz()
{
   # get system's time zone, by looking at the
   # destination of the /etc/localtime symlink

   timezone="$(readlink /etc/localtime)"
   timezone="$(cd /etc && realpath -m -s "$timezone")"
   printf "${timezone#/usr/share/zoneinfo/}"
}


gui=
long=
while getopts glh opt
do
   case $opt in
       g) gui=1 ;;
       l) long=1 ;;
       h) usage 0 ;;
       *) usage 2 ;;
   esac
done

shift $(($OPTIND - 1))
if [ "$#" -gt 0 ]; then
   usage 1
fi


if [ ! -f "$tzdata" ]; then
   msg=$(cat <<EOF
error: time zone data not found at $tzdata

note: you can set the 'tzdata' variable to point to the location of tzdata.zi
EOF
      )
   say "$msg"
   exit 1
fi

# current time zone per $TZ, falling back to system's
tz="${TZ:-$(systemtz)}"

# all time zones known to the system
zonenames="$(awk '/^Z/ { print $2 } /^L/ { print $3 }' $tzdata)"

datefrom="$(ask '' 'Convert date/time ')"

tzfrom="$(ask "$zonenames" 'in time zone ' "$tz")"

tzto=
if [ "$tzfrom" = "$tz" ]; then
   tzto="$(ask "$zonenames" 'to time zone ')"
else
   tzto="$(ask "$zonenames" 'to time zone ' "$tz")"
fi

dateto="$(TZ="$tzto" date --date="TZ=\"$tzfrom\" $datefrom")"

if [ "$long" ]; then
   say "$datefrom ($tzfrom) is $dateto ($tzto)"
else
   say "$dateto"
fi