#!/bin/bash
#                       /usr/local/bin/astrolog
# https://crystalfaeries.net/posix/bin/astrolog
# celeste:crystalfaery ASTROLOG 2019-08-28 17:15:43+00:00
# a bash shell wrapper around use of /usr/local/games/astrolog/astrolog

exit	255	# i don't have a compiled version of astrolog on DebIan10+

# Invocation with no arguments:
# generate current calendar report for website
# generate current time-space file for astrolog
# (used also by manual invocations for astrolog)
# generate current astrolog chart for website
# generate current astrolog report for website
# generate current weather report for website
# this should be invoked every 15 minutes by cron;
# (if you change the period here, change also the refresh line for the generated html):
# 09,24,39,54 * * * * /usr/local/bin/astrolog 2>> $HOME/.chronicle.log 1>&2

# Optional Arguments specify the date and time of the astrolog chart to be generated (then quit),
# optionally followed by the event name, e.g. Full_Moon, (no spaces) (default="Today"):
# astrolog 2017 Aug 21 06:17 Full_Moon

# Optional Arguments are "-d" and the date+time arguments, to delete a previously generated astrolog, and quit.
# astrolog -d 2017 Aug 21 06:17

# Optional Argument is "-g" to generate an image gallery for the astrolog directory and quit.

# Optional Argument is "-m" to generate charts for all {Full,New} Moons this calendar year and quit.

# NOTES for the Intrepid Hacker:
# /imgs/clipart/portrait/astrolog.png is not yet referenced, it would be good to add it to today.html!
# Calculating "bletch" is hard coded to HST Time-Zone... edit for your own!

let help=32 # (this file's line number of this line) -1

# DANGER, DANGER, WILL ROBINSON! This script is not only RECURSIVE,
# but may be asynchronously called MANUALLY and by CRONTAB!
# we MUST lock the use of the kilauea.txt file!
lockfile=/run/lock/.$(basename $0)
let lockretry=32 # I have no idea what the time-scale is, but increase if lock retry timeouts happen.

# install ERROR / EXIT HANDLER:
let exitval=0 # default to success
function cleanup {

	# remove temporary files:
	for f in /tmp/{*.,}$${,.txt}
	do  # spawn a ReMove process for each of our temporary files so we can exit soon.
	    if [ -w	 "${f}" ]
	    then
		nohup rm "${f}"	</dev/null >&/dev/null & disown %1 # in the background
	    fi
	done

	# remove lock file:
	nohup filelock -u -r ${lockretry} ${lockfile} </dev/null >&/dev/null & disown %1
	let exitval=$?
	exit $exitval
}
trap cleanup 0 1 2 15 # activate error handler

# Our run LOG is (for now) that of chronicle.
LOG="${HOME}/.chronicle.log"

# ASTROLOG output directory is where we work:
cd -P ${HOME}/crystalfaeries.net/astrolog/ 2>> ${LOG} 1>&2

if [[ $# -eq 0 ]] ; then # THERE ARE NO ARGUMENTS TO PROCESS, JUST DO THE CURRENT CHART (EVERY 15 MINUTES)

	:	# this broken code has been pulled out for debugging, now at astrolog.noarg, return by pieces

else # OH! WE HAVE AN ARGUMENT! LET'S HOPE WE WIN? :-)

    case "${1}" in
-v) head -n 4 $0 | tail -n 1 # just the date line
	let exitval=$?
	exit $exitval
	;;
--version) head -n 4 $0 | tail -n 1 # just the date line
	let exitval=$?
	exit $exitval
	;;
-h) head -n $help $0 # the whole header of comments
	let exitval=$?
	exit $exitval
	;;
--help) head -n $help $0 # the whole header of comments
	let exitval=$?
	exit $exitval
	;;
-g) # Generate an image gallery for the astrolog directory and quit:
	echo 'ASTROLOG GALLERIES BEGIN' 2>> ${LOG} 1>&2 || exit -18 # Error: 238 Can't write Log
	igal2 -i gallery.html 2>> ${LOG} 1>&2 || rm gallery.html # Error: 237 No Images
	if [ -s gallery.html ]
	then
		cat ${HOME}/crystalfaeries.net/README.html >> gallery.html 2>> ${LOG} || exit -20 # Error: 236 igal2 /imgs/gallery.html
		echo "gallery index was updated in `pwd`" 2>> ${LOG} 1>&2 || exit -21 # Error: 235 Require writeable log file
		let exitval=$?
	else
		echo "gallery index was deleted in `pwd` for lack of images." 2>> ${LOG} 1>&2 || exit -21 # Error: 235 Require writeable log file
		let exitval=$?
	fi
	exit $exitval
	;;
-m) # generate charts for all {Full,New} Moons this calendar year and quit.
	LOCATION="Hanalei" # the nearest xtide location
	if [ ! -x `which calendar` ]
	then
		echo "astrolog requires installation of 'calendar'" 2>> ${LOG} 1>&2
		sudo apt-get install calendar
	fi
	if [ ! -x `which tide` ]
	then
		echo "astrolog requires installation of 'calendar'" 2>> ${LOG} 1>&2
		sudo apt-get install tide xtide
	fi
	mv $HOME/.calendar/calendar $HOME/.calendar/calendar~
	grep -v "Full Moon" $HOME/.calendar/calendar~ | grep -v "New Moon" >> /tmp/$$
	year="`date +%Y`"
	tide -l "$LOCATION" -b "$year-01-01 00:00" -e "$year-12-31 23:59" 2>> ${LOG} | grep Moon | grep -v Moonrise | grep -v Moonset | sed "s/ / /;s/^$year-//g;s/-/ /g;s/ / /g;s/ / /g;s/ / /g;s/ New Moon/ New Moon/g;s/ Full Moon/ Full Moon/g" >> /tmp/$$
	echo "LANG=UTF-8" >> $HOME/.calendar/calendar
	grep -v "LANG" /tmp/$$ | sort -u | sort -n >> $HOME/.calendar/calendar
	the_year=$( date +'%Y' )
	let exitval=$? ; if [[ $exitval -ne 0 ]] ; then exit $exitval ; fi # ERROR EXIT
	grep "Full Moon" $HOME/.calendar/calendar | sed 's/Full Moon/Full_Moon/g' | sed 's/ / /' | sed "s/^/${the_year} /" > /tmp/moons.$$.txt
	let exitval=$? ; if [[ $exitval -ne 0 ]] ; then exit $exitval ; fi # ERROR EXIT
	grep "New Moon" $HOME/.calendar/calendar | sed 's/New Moon/New_Moon/g' | sed 's/ / /' | sed "s/^/${the_year} /" >> /tmp/moons.$$.txt
	let exitval=$? ; if [[ $exitval -ne 0 ]] ; then exit $exitval ; fi # ERROR EXIT
	sort -n -k1,3 /tmp/moons.$$.txt | while read lunation
	do
		first="$(echo "${lunation}" | cut -f1)" # Year
		let exitval=$? ; if [[ $exitval -ne 0 ]] ; then exit $exitval ; fi # ERROR EXIT
		second="$(echo "${lunation}" | cut -f2)" # Month
		let exitval=$? ; if [[ $exitval -ne 0 ]] ; then exit $exitval ; fi # ERROR EXIT
	    case "${second}" in
		01) month="Jan";;
		02) month="Feb";;
		03) month="Mar";;
		04) month="Apr";;
		05) month="May";;
		06) month="Jun";;
		07) month="Jul";;
		08) month="Aug";;
		09) month="Sep";;
		10) month="Oct";;
		11) month="Nov";;
		12) month="Dec";;
		*) let exitval="${second}"
		 exit $exitval;; # ERROR EXIT
	    esac
		let exitval=$? ; if [[ $exitval -ne 0 ]] ; then exit $exitval ; fi # ERROR EXIT
		third="$(echo "${lunation}" | cut -f3)" # Day
		let exitval=$? ; if [[ $exitval -ne 0 ]] ; then exit $exitval ; fi # ERROR EXIT
		fourth="$(echo "${lunation}" | cut -f4 | sed 's/ HST//;s/:[0-9][0-9] //')" # MY LOCAL TIME ZONE
		let exitval=$? ; if [[ $exitval -ne 0 ]] ; then exit $exitval ; fi # ERROR EXIT
	    case "${fourth}" in
		12AM) hour="00";;
		1AM) hour="01";;
		2AM) hour="02";;
		3AM) hour="03";;
		4AM) hour="04";;
		5AM) hour="05";;
		6AM) hour="06";;
		7AM) hour="07";;
		8AM) hour="08";;
		9AM) hour="09";;
		10AM) hour="10";;
		11AM) hour="11";;
		12PM) hour="12";;
		1PM) hour="13";;
		2PM) hour="14";;
		3PM) hour="15";;
		4PM) hour="16";;
		5PM) hour="17";;
		6PM) hour="18";;
		7PM) hour="19";;
		8PM) hour="20";;
		9PM) hour="21";;
		10PM) hour="22";;
		11PM) hour="23";;
		*) let exitval=24
		 exit $exitval;; # ERROR EXIT
	    esac
		bletch="$(echo "${lunation}" | cut -f4 | sed "s/ HST//;s/^.*:/${hour}:/;s/ AM//;s/ PM//")"
		daytime="${first} ${month} ${third} ${bletch}"
		let exitval=$? ; if [[ $exitval -ne 0 ]] ; then exit $exitval ; fi # ERROR EXIT
		event="$(echo "${lunation}" | cut -f5)" # Event Name (no spaces allowed!)
		let exitval=$? ; if [[ $exitval -ne 0 ]] ; then exit $exitval ; fi # ERROR EXIT
	    /usr/local/bin/astrolog "${daytime}" "${event}" # CALCULATE THE LUNATION! (RECURSIVE!)
		# let exitval=$? ; if [[ $exitval -ne 0 ]] ; then exit $exitval ; fi # ERROR EXIT
	done && rm /tmp/moons.$$.txt
	# let exitval=$? ; if [[ $exitval -ne 0 ]] ; then exit $exitval ; fi # ERROR EXIT
	exit 0 # Fail? Hah! Not with multiple charts to run :-)
	;;
-d) shift # consume the -d argument
	# remove the astrolog chart wheel and interpretation
	the_year="${1}"
	the_month="${2}"
	the_day="${3}"
	the_time="${4}"
	the_date=$(date --rfc-3339=date --date="${the_month} ${the_day} ${the_year}")
	the_htmlfile="crystalfaeries.net/astrolog/${the_date}.$(echo ${the_time}|sed 's/:/-/').html"
	optimized_image="crystalfaeries.net/astrolog/${the_date}.$(echo ${the_time}|sed 's/:/-/').png"
	delete "${the_htmlfile}" "${optimized_image}"
	let exitval=$?
	exit $exitval
	;;
*)	:
	############################################################################
	# ARGUMENTS constitute a date+time spec in the format of 2017 Aug 21 06:17 #
	# followed by a single event name not broken by spaces, e.g.: Full_Moon    #
	############################################################################
	 the_year="${1}"
	the_month="${2}"
	  the_day="${3}"
	 the_time="${4}"
	the_event="${5}"
	the_date=$(date --rfc-3339=date --date="${the_month} ${the_day} ${the_year}")
	the_image="${HOME}/crystalfaeries.net/astrolog/${the_date}.$(echo ${the_time}|sed 's/:/-/').bmp"
	the_chart="${HOME}/crystalfaeries.net/astrolog/${the_date}.$(echo ${the_time}|sed 's/:/-/').png"
	 the_file="${HOME}/crystalfaeries.net/astrolog/${the_date}.$(echo ${the_time}|sed 's/:/-/').html"

	# ASTROLOG HEADER:
	echo '<html><head><title>crystalfaeries Astrology + Weather</title><meta http-equiv="refresh" content="900"></head>' > "${the_file}" 2>> ${LOG}
	echo '<body bgcolor="#000000" text="#FFFFFF" vlink="#FFFFFF" alink="#333333" link="#CCCCCC">' >> "${the_file}" 2>> ${LOG}
	echo '<a href="/fae/phases.html"><img src="/astrolog/moon.png" alt="[moon phase]" align="left" width="95" height="95"></a>' >> "${the_file}" 2>> ${LOG}
	echo '<p align="left"><a href="https://duckduckgo.com/">https://</a><a href="/">crystalfaeries.net/</a><a href="/astrolog/">astrolog/</a><a href="/astrolog/today.html">today.html</a></p>' >> "${the_file}" 2>> ${LOG}
	echo '<h1 align="center"><a href="/fae/">crystalfaeries</a> <a href="http://www.leapsecond.com/java/gpsclock.htm">Chronology</a></h1>' >> "${the_file}" 2>> ${LOG}
	echo '<br clear="all">' >> "${the_file}" 2>> ${LOG}
	echo -n '<a href="/astrolog/gallery.html"><img src="' >> "${the_file}" 2>> ${LOG}
	echo -n "${the_chart}" >> "${the_file}" 2>> ${LOG}
	echo '" align="left" width="640" height="480"></a>' >> "${the_file}" 2>> ${LOG}
	echo '<br clear="all">' >> "${the_file}" 2>> ${LOG}
	echo "<pre>" >> "${the_file}" 2>> ${LOG}

	# ASTROLOG TIME-SPACE file:
    pushd /usr/local/games/astrolog/	2>> ${LOG} 1>&2
filelock -l -r ${lockretry} ${lockfile}	2>> ${LOG} 1>&2

	echo '@0103 ; Astrolog chart info.' > kilauea.txt 2>> ${LOG}
	echo "-qb ${the_month} ${the_day} ${the_year} ${the_time} ST 10:00W 159:24W 22:13N" >> kilauea.txt 2>> ${LOG}
	echo '-zi "Today" "Kilauea"' >> kilauea.txt 2>> ${LOG}

	# generate the ASTROLOG CHART:
	/usr/local/games/astrolog/astrolog -YQ 32765 -Yt -I -i kilauea.txt -Xbb -Xo "${the_image}" 2>> ${LOG} 1>&2
	let exitval=$? ; if [[ $exitval -ne 0 ]] ; then exit $exitval ; fi # ERROR EXIT
	convert "${the_image}" "${the_chart}" 2>> ${LOG} 1>&2 && rm "${the_image}" 2>> ${LOG} 1>&2
	let exitval=$? ; if [[ $exitval -ne 0 ]] ; then exit $exitval ; fi # ERROR EXIT

	# generate the ASTROLOG ANALYSIS:
	if [ "${the_event}" == "" ]
	then # no event name, defaults to "Today"
		/usr/local/games/astrolog/astrolog -v -g0 -j0 -7 -d -D -Yt -Zd -I -YQ 32765 -i kilauea.txt >> "${the_file}" 2>> ${LOG}
			let exitval=$? ; if [[ $exitval -ne 0 ]] ; then exit $exitval ; fi # ERROR EXIT
	else # replace "Today" with "${the_event}"
		/usr/local/games/astrolog/astrolog -v -g0 -j0 -7 -d -D -Yt -Zd -I -YQ 32765 -i kilauea.txt | sed "s/Today/${the_event}/g" >> "${the_file}" 2>> ${LOG}
	fi
	let exitval=$? ; if [[ $exitval -ne 0 ]] ; then exit $exitval ; fi # ERROR EXIT
	echo "</pre>" >> "${the_file}"	2>> ${LOG}

	# FOOTER:
	cat ${HOME}/crystalfaeries.net/README.html >> "${the_file}" 2>> ${LOG}
	let exitval=$? # really only the results of the final cat, due to lazy coding :-)
	
filelock -u -r ${lockretry} ${lockfile}	2>> ${LOG} 1>&2	# UNLOCK
    popd				2>> ${LOG} 1>&2
astrolog -g	< /dev/null		2>> ${LOG} 1>&2	& disown %1 # update the astrolog gallery index
    ;;
    esac # Did we process arguments?
fi # Did we win the arguments?
let exitval=$? ; if [[ $exitval -ne 0 ]] ; then exit $exitval ; fi # ERROR EXIT

# rsync -auvzH ${HOME}/crystalfaeries.net/astrolog `my_twin`:~/crystalfaeries.net 2>> ${LOG} 1>&2
# let exitval=$? ; if [[ $exitval -ne 0 ]] ; then exit $exitval ; fi # ERROR EXIT

exit $exitval # Pau for now
