#!/bin/bash
#                       /usr/local/bin/astrolog
# https://crystalfaeries.net/posix/bin/astrolog
# celeste:crystalfaery ASTROLOG 2019-07-31 19:13:38+00:00
# a bash shell wrapper around use of /usr/local/games/astrolog/astrolog

# 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 lock file:
	nohup filelock -u -r ${lockretry} ${lockfile} </dev/null >&/dev/null & disown %1

	# 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

	# return any error code:
	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

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

	# ASTROLOG HEADER:
# (if you change the period here, change also the crontab entries for astrolog):
	echo '<html><head><title>crystalfaeries Astrology + Weather</title><meta http-equiv="refresh" content="900"></head>' > today.html 2>> ${LOG}
	echo '<body bgcolor="#000000" text="#FFFFFF" vlink="#FFFFFF" alink="#333333" link="#CCCCCC">' >> today.html 2>> ${LOG}
	echo '<a href="http://crystalfaeries.net:8080/locations/Hanalei"><img src="/clipart/matthewg42_lighthouse.png" alt="[Tides]" align="left" border="0" width="36" height="144"></a>' >> today.html 2>> ${LOG}
	echo '<a href="/fae/phases.html"><img src="/astrolog/moon.png" alt="[moon phase]" align="left" border="0" width="95" height="95"></a>' >> today.html 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/gallery.html">today.html</a></p>' >> today.html 2>> ${LOG}
	echo '<a href="/rawdog.html"><img align="left" alt="[News]" width="96" height="96" src="/clipart/dog_with_a_rolled_up_newspaper_in_its_mouth_blackground.jpg"></a>' >> today.html 2>> ${LOG}
	echo '<a href="http://crystalfaeries.net:8000/"><img alt="[IceCast2]" width="90" height="96" align="left" src="/imgs/clipart/portrait/icecast.png"></a>' >> today.html 2>> ${LOG}
	echo '<h1 align="center"><a href="/fae/">crystalfaeries</a> <a href="http://www.leapsecond.com/java/gpsclock.htm">Chronology</a></h1>' >> today.html 2>> ${LOG}
	echo '<p align="center">This page auto-updates every 15 minutes.</p>' >> today.html 2>> ${LOG}
	echo '<br clear="all">' >> today.html 2>> ${LOG}
	echo '<a href="/astrolog/gallery.html"><img src="/astrolog/astro.png" align="left" alt="[Astrolog Chart Wheel]" width="640" height="480"></a><br clear="all">' >> today.html 2>> ${LOG}
	echo "<pre>" >> today.html 2>> ${LOG}
	echo " <a href="/astrolog/today.html">`date +'%Y-%m-%d'`</a>" >> today.html 2>> ${LOG}

	# CAL
	/usr/bin/cal -A1 | sed 's/_//g' >> today.html 2>> ${LOG}
	let exitval=$? ; if [[ $exitval -ne 0 ]] ; then exit $exitval ; fi # ERROR EXIT

	# CALENDAR + TRIWEEKLY EVENTS
	if [ -x `which calendar` ]
	then
		events	>> today.html 2>> ${LOG} || exit $? # calendar used by events
	else
		echo "astrolog requires installation of 'calendar'" 2>> ${LOG} 1>&2
		sudo apt-get install calendar
	fi

	# Include the Hanalei Bay Tides for the next few days:
	if [ -x `which tide` ]
	then
		echo ""				>> today.html	2>> ${LOG}
		/usr/bin/tide -m c -l hanalei	>> today.html	2>> ${LOG}
		echo ""				>> today.html	2>> ${LOG}
	else
		echo "astrolog requires installation of 'tide'"	2>> ${LOG} 1>&2
		sudo apt-get install tide xtide
	fi
	
    pushd /usr/local/games/astrolog/	2>> ${LOG} 1>&2 # astrolog must be run in it's dir.
filelock -l -r ${lockretry} ${lockfile}	2>> ${LOG} 1>&2 # we MUST lock use of kilauea.txt

	# generate current ASTROLOG TIME-SPACE file
	echo '@0103 ; Astrolog chart info.' > kilauea.txt 2>> ${LOG}	# rebuild our chart control file
	echo "-qb `date +'%b %d %Y %H:%M'` ST 10:00W 159:24W 22:13N" >> kilauea.txt 2>> ${LOG}
	echo '-zi "Today" "Kilauea"' >> kilauea.txt 2>> ${LOG}

	# generate current ASTROLOG CHART:
	/usr/local/games/astrolog/astrolog -YQ 32765 -Yt -I -i kilauea.txt -Xbb -Xo ${HOME}/crystalfaeries.net/astrolog/astro.bmp 2>> ${LOG} 1>&2
	let exitval=$? ; if [[ $exitval -ne 0 ]] ; then exit $exitval ; fi # ERROR EXIT
	if [ -s ${HOME}/crystalfaeries.net/astrolog/astro.bmp ] 
	then
		convert	${HOME}/crystalfaeries.net/astrolog/astro.bmp ${HOME}/crystalfaeries.net/astrolog/astro.png 2>> ${LOG} 1>&2 && rm	${HOME}/crystalfaeries.net/astrolog/astro.bmp 2>> ${LOG} 1>&2
	let exitval=$? ; if [[ $exitval -ne 0 ]] ; then exit $exitval ; fi # ERROR EXIT

	# generate current ASTROLOG ANALYSIS:
	/usr/local/games/astrolog/astrolog -v -g0 -j0 -7 -d -D -Yt -Zd -I -YQ 32765 -i kilauea.txt 2>> ${LOG} >> ${HOME}/crystalfaeries.net/astrolog/today.html
	let exitval=$? ; if [[ $exitval -ne 0 ]] ; then exit $exitval ; fi # ERROR EXIT

filelock -u -r ${lockretry} ${lockfile} 2>> ${LOG} 1>&2
    popd				2>> ${LOG} 1>&2
	echo '</pre>' >> today.html 2>> ${LOG}

	# WEATHER:
	echo '<a name="weather"><a href="http://www.prh.noaa.gov/hnl/satellite/Hawaii_IR_loop.gif"><img src="http://www.ssd.noaa.gov/goes/west/hi/rb.jpg" align="left" alt="[GOES West Rainbow Infra-Red Ch.4]" width="720" height="480"></a></a>' >> today.html 2>> ${LOG}
	echo '<br clear="all">' >> today.html 2>> ${LOG}
	echo '<a href="http://weather.hawaii.edu/satellite/still.cgi?product=satellite&res=4km&banner=uhmet&chnl=ir&domain=hus&size=large&satplat=goeswest&anim=no&overlay=on"><img src="http://www.prh.noaa.gov/hnl/satellite/latest/CPAC_IR.gif" align="left" alt="[Central Pacific Huricane Center Infra-Red satellite image]" width="525" height="420"></a>' >> today.html 2>> ${LOG}
	echo '<br clear="all">' >> today.html 2>> ${LOG}
	echo '<a href="http://www.hamqsl.com/solar.html" title="Click to add Solar-Terrestrial Data to your website!"><img src="http://www.hamqsl.com/solargraph.php" align="left"></a><br clear="left">' >> today.html 2>> ${LOG}
	echo '<a name="charts"><br clear="all"></a>' >> today.html 2>> ${LOG}
	echo '<br clear="all">' >> today.html 2>> ${LOG}

	# Index the charts we have:
	echo '<h1 align="center"><a href="/fae/">Astrological Charts Past+Future</a></h1>' >> today.html 2>> ${LOG}
	echo '<ul>'	>> today.html 2>> ${LOG}
	for chart in ${HOME}/crystalfaeries.net/astrolog/{19,20}[1-9]*.html
	do
		echo -n '<li><a href="' >> today.html 2>> ${LOG}
		echo -n "/astrolog/$(basename ${chart})" >> today.html 2>> ${LOG}
		echo -n '">' >> today.html 2>> ${LOG}
		echo -n "$(basename ${chart} | sed 's/\.html$//'): " >> today.html 2>> ${LOG}
		echo -n "$(grep "Astrolog chart for " ${chart} | sed 's/^.*://;s/Astrolog chart for //')" >> today.html 2>> ${LOG}
		echo "</a></li>" >> today.html 2>> ${LOG}
	done
	echo '</ul>'	>> today.html 2>> ${LOG}

	# FOOTER:
	cat ${HOME}/crystalfaeries.net/README.html >> today.html 2>> ${LOG}
	let exitval=$? ; if [[ $exitval -ne 0 ]] ; then exit $exitval ; fi # ERROR EXIT

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:
	# generate current 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
filelock -u -r ${lockretry} ${lockfile} 2>> ${LOG} 1>&2
	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 :-)
	
	astrolog -g # update the gallery index (NOT done on our every 15 minutes update of today.html) (RECURSIVE!)
    popd	2>> ${LOG} 1>&2
	;;
    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

