#!/usr/bin/env sh

# moonphase-date v0.2
# return stylized moonphase and current date timestamp

# option flags
unset invert year html now
for f in $(echo "${@#-}" | sed 's/./& /g'); do
	case $f in
		i) invert=1;; # for reverse video moon phase
		y) year=1;; # include year in output
	esac
done
for f in "$@"; do case "$f" in
	[1-9][0-9]*) now="$f";; # use specific unix date instead of now
esac; done
[ ! -z "$now" ] || now="$(date '+%s')"

# calculate days since a specific new moon
# divide by length of lunar cycle
# express currently elapsed cycle progress in percent
known=633381600 # Jan 26th, 1990 was a new moon
cycle=$(echo "scale=2; (($now - $known) / 86400) / 29.53" | bc)
cycle=${cycle#*.} # absolute value
# map cycle progress to an available glyph
# reverse video: switch new/full moon glyphs for use with dark backgrounds
phases='๐ŸŒ‘ ๐ŸŒ’ ๐ŸŒ“ ๐ŸŒ” ๐ŸŒ•\n๐ŸŒ• ๐ŸŒ– ๐ŸŒ— ๐ŸŒ˜ ๐ŸŒ‘'
map=$(((${cycle#0} / 10) + 1))
moon=$(echo "$phases" | sort ${invert:+-r} | tr ' ' '\n' \
	| tail -n +$map | head -n 1)

# current date
format="+%-e %a, %b ยต${year:+, %Y}"
timest="$(date -d "1970-01-01 UTC $now seconds" "$format")"
day="${timest%% *}"
case $day in
	1 | [!1]1) day="${day}st";;
	2 | [!1]2) day="${day}nd";;
	3 | [!1]3) day="${day}rd";;
	*) day="${day}th"
esac
echo "$moon ${timest#* }" | sed "s/ยต/$day/"