#!/bin/bash

set -e

LIBRARY=/var/www/html/library

WEBSITE=/var/www/html/hugopiratecare
[ -d $WEBSITE ] || mkdir -p $WEBSITE

WEBSITEPREVIEW=/var/www/html/hugopiratecare/_preview/
[ -d $WEBSITEPREVIEW ] || mkdir -p $WEBSITEPREVIEW

GIT_URL="https://git.memoryoftheworld.org/PirateCare/Syllabus"
HUGO_PREVIEW_URL="https://syllabus.pirate.care/_preview/"

GIT_PATH="git"
HUGO_PATH="hugo"

BRK="krb"
SAVEIFS=$IFS

TMP_WEBSITE=/tmp/website$RANDOM
TMP_WEBSITEPREVIEW=/tmp/websitepreview$RANDOM

d=`date`
CWD=`pwd`

while read oldrev newrev ref
do
	refs=`$GIT_PATH diff-tree --no-commit-id --name-only $ref`
	IFS=$'\n'
	r=($refs)

	for (( i=0; i<${#r[@]}; i++ ))
	do
		if [ ${r[$i]} = "PUBLISH.trigger.md" ]; then
			cd $CWD
			$GIT_PATH clone . $TMP_WEBSITE
			cd $TMP_WEBSITE
			[ -d $WEBSITE ] || mkdir -p $WEBSITE

                        if [ -d $WEBSITE ]
	                  then
			                  safe-rm -rf ${WEBSITE}*
                        fi

			$HUGO_PATH -e gitea -d $WEBSITE > ${TMP_WEBSITE}/last-commit-log.txt
			printf "\n>> $d\n>> `date`" >> ${TMP_WEBSITE}/last-commit-log.txt
			mv ${TMP_WEBSITE}/last-commit-log.txt $WEBSITE
			cd /tmp/

                        if [ -d $TMP_WEBSITE ]
	                  then
			    safe-rm -rf $TMP_WEBSITE
                        fi
			BRK="brk"
			break
		fi
	done

	if [ $BRK = "brk" ]; then
		break
	fi
	
	cd $CWD
	refs=`$GIT_PATH show --format="%s" -s`
	IFS=$' '
	r=($refs)
	for (( i=0; i<${#r[@]}; i++ ))
	do
		if [ ${r[$i]} = "!publish!" ]; then
			$GIT_PATH clone . $TMP_WEBSITE
			cd $TMP_WEBSITE

			[ -d $WEBSITE ] || mkdir -p $WEBSITE

                        if [ -d $WEBSITE ]
	                  then
			    safe-rm -rf ${WEBSITE}*
                        fi

			$HUGO_PATH -e gitea -d $WEBSITE > ${TMP_WEBSITE}/last-commit-log.txt
			printf "\n>> $d\n>> `date`" >> ${TMP_WEBSITE}/last-commit-log.txt
			mv $TMP_WEBSITE/last-commit-log.txt $WEBSITE
			cd /tmp/

			if [ -d $TMP_WEBSITE ]; then
				safe-rm -rf $TMP_WEBSITE
			fi

			break
		fi
	done
done

cd $CWD
$GIT_PATH clone . $TMP_WEBSITEPREVIEW
cd $TMP_WEBSITEPREVIEW

[ -d $WEBSITEPREVIEW ] || mkdir -p $WEBSITEPREVIEW
[ -d data ] || mkdir -p data

echo 'edit = true' > data/myvars.toml
echo 'giturl="'${GIT_URL}'"' >> data/myvars.toml

if [ -d $WEBSITEPREVIEW ]
  then
    safe-rm -rf $WEBSITEPREVIEW
fi


$HUGO_PATH -e gitea -d $WEBSITEPREVIEW > ${TMP_WEBSITEPREVIEW}/last-commit-log.txt
printf "\n>> $d\n>> `date`" >> ${TMP_WEBSITEPREVIEW}/last-commit-log.txt
mv ${TMP_WEBSITEPREVIEW}/last-commit-log.txt $WEBSITEPREVIEW

if [ -d $TMP_WEBSITEPREVIEW ]
  then
    safe-rm -rf $TMP_WEBSITEPREVIEW
fi

ln -sf $LIBRARY $WEBSITE
ln -sf $LIBRARY $WEBSITEPREVIEW

IFS=$SAVEIFS
