#!/usr/bin/bash

# started building an index generator 2022/02/22

##       __________________   __________________
##   .-/|                  \ /                  |\-.
##   ||||                   |                   ||||
##   ||||                   |                   ||||
##   ||||   Books           |   Ramblings and   ||||
##   ||||                   |   recollections   ||||
##   ||||     Books         |    about books    ||||
##   ||||                   |     libraries     ||||
##   ||||        Books      |      reading      ||||
##   ||||                   |        and        ||||
##   ||||                   |         ♥         ||||
##   ||||                   |                   ||||
##   ||||__________________ | __________________||||
##   ||/===================\|/===================\||
##   `--------------------~___~-------------------''

HOME='/home/booksbooksbooks'
static_gemini='/home/booksbooksbooks/static-gemini'
capsule_address='gemini://gemini.ctrl-c.club/~booksbooksbooks'
date_format="%F @ %H:%M"
index_body=""

## back-up the public_gemini folder
echo -e "backing up capsule"

cp -r $HOME/public_gemini/ $HOME/public_gemini_bak/

for page in $(ls $static_gemini/*.gmi | shuf)
do
	page_basename=$(basename $page) 
	page_title=$(head --lines=1 $page) # first line contains the title for index
	tail --lines=+2 $page > $static_gemini/$page_basename.body # second line onwards contains the body
	
	echo "processing: $page"

	cat 	$static_gemini/templates/page.header\
	       	$static_gemini/$page_basename.body\
	       	$static_gemini/templates/page.footer > $HOME/public_gemini/$page_basename

	echo -e "This page was last modified on $(date -r $page +"$date_format")." >> $HOME/public_gemini/$page_basename

	## Add the page to the index page body.
	index_body+="=> $capsule_address/$page_basename $page_title \n"
done

echo -e "processed $(ls $static_gemini/*.gmi | wc -l) pages."

## Assemble the index page from header / body / footer

echo -e $index_body > $HOME/static-gemini/index.body

cat 	$static_gemini/templates/index.header\
	$static_gemini/index.body\
	$static_gemini/templates/index.footer > $HOME/public_gemini/index.gmi

echo -e "This index page was generated on $(date +"$date_format")." >> $HOME/public_gemini/index.gmi

echo -e "built the index"

## Clean-up all the bodies

rm $static_gemini/*.body

