#!/bin/bash
#                   /usr/local/bin/recently_linked
# https://crystalfaeries/posix/bin/recently_linked
# celeste:crystalfaery RECENTLY_LINKED 2021-04-28 16:04:12+00:00
# recently_linked generates a webpage indexing by date (inverse order)
# the URLs linked-to from webpages in the blog generated by chronicle (ignores rest of website)
# this is primarily invoked during the run of /usr/local/bin/blog,
# so that upon each regeneration of the blog we update the link date page.
# NOTE: first hack of code will fail to see more than one URL per line of text.
let help=9	# this line number - 1
case $# in
0)	:	# No arguments, just fall through and do it
	;;
*)	head -n $help $0
	exit	# cannonical help response
	;;
esac

# The DATABASE of external links is simply two columns of text:
# 1:	UNIX TimeStamp
# 2:	URL
DATABASE=$HOME/crystalfaeries.net/links.txt
touch	${DATABASE}				|| exit 1	# write permission required

# Update the URL DataBase which is sorted oldest first to newest last:
for URL in $(grep 'href="http' "${HOME}"/crystalfaeries.net/src/*.txt | grep -v http://crystalfaeries.net/ | grep -v https://crystalfaeries.net/ | sed 's/^.*http:\/\//http:\/\//g ; s/^.*https:\/\//https:\/\//g ; s/".*$//g ; s/<\/a>.*$//g ; s/\[.*$//g');
do
	grep -i	"${URL}"	${DATABASE}	>  /dev/null
	if [ $? -ne 0 ]
	then
		echo "`date +%s`	${URL}"	>> ${DATABASE}
	fi
done

# Generate the HTML page:
echo '<html><head><title>Recently Linked</title><meta http-equiv="refresh" content="86400;url=/recently_linked.html"></head><body bgcolor="#000000" text="#FFFFFF" vlink="#FFFFFF" alink="#333333" link="#CCCCCC"><a href="/"><h1 align="center">Recently Linked</h1></a>' \
						>  $HOME/crystalfaeries.net/recently_linked.html	# Title and Header
echo '<a href="/celeste/recently_bookmarked.html"><img src="/imgs/clipart/portrait/clock.png" alt="[clock]" align="right" width="219" height="219"></a>' \
						>> $HOME/crystalfaeries.net/recently_linked.html	# Title and Header
echo '<p>Date______	Time-Timezone	URL<br>'	>> $HOME/crystalfaeries.net/recently_linked.html	# Column Headings

# read URLs newest to oldest
tac ${DATABASE}	|	\
while	read STAMP URL
do
	echo "$(date --rfc-3339=seconds --date=@${STAMP})	<a href=\"${URL}\">${URL}</a><br>"	\
						>> $HOME/crystalfaeries.net/recently_linked.html
done

echo -e "</p>"					>> $HOME/crystalfaeries.net/recently_linked.html
cat	$HOME/crystalfaeries.net/README.html	>> $HOME/crystalfaeries.net/recently_linked.html
exit	$?

