#!/bin/sh
set -e -u -o pipefail
#set -v

# run this from a directory outside the script directory
# as it will clone the repo and create general mess
# plus it will nuke anything called root

SRCDIR=$(dirname $0)
DESTDIR=$(pwd)

generate_file_etag() {
	file=$1
	prefix=$2
	# trim: ./ -> /
	WEB_PATH=$(echo $file | cut -c 2-)
	SHA=$(shasum $file | awk '{print $1}')
	echo "$prefix$WEB_PATH	\"$SHA\";"
}

generate_directory_etag() {
	dir=$1
	prefix=$2
	# trim: ./ -> /
	WEB_PATH=$(echo $dir | cut -c 2-)
	SHA=$(shasum $dir/index.html | awk '{print $1}')
	echo "$prefix$WEB_PATH/	\"$SHA\";"
}

generate_etags() {
	prefix=$1
	find . -type f | while read -r file; do
		generate_file_etag "$file" "$prefix"
	done | tee -a $DESTDIR/root/usr/local/etc/nginx/etag.map
	find . -type d | while read -r dir; do
		if [ -e $dir/index.html ]; then
			generate_directory_etag "$dir" "$prefix"
		fi
	done | tee -a $DESTDIR/root/usr/local/etc/nginx/etag.map
}

# clean and create the output dirs
rm -rf root
mkdir -p root/usr/local/www/git
mkdir -p root/usr/local/etc
mkdir -p root/etc/newsyslog.conf.d

# copy in the syslog and nginx conf
cp $SRCDIR/newsyslog/* root/etc/newsyslog.conf.d/
cp -r $SRCDIR/nginx root/usr/local/etc

# generate the blog files
pushd $SRCDIR/blog
hugo --cleanDestinationDir=true --minify=true
popd

# move that in
mv $SRCDIR/blog/public/ root/usr/local/www/blog

# generate the etags
pushd root/usr/local/www/blog
generate_etags ""
popd

# get a www.git git checkout and update it for dumb transport
git clone --no-hardlinks --bare $SRCDIR root/usr/local/www/git/www.git
git -C root/usr/local/www/git/www.git remote remove origin
git -C root/usr/local/www/git/www.git update-server-info

# generate static site
pushd root/usr/local/www/git/www.git
~/go/bin/gitmal --minify .
mv output ../www
popd

# get a gitmal.git git checkout and update it for dumb transport
# (assumes it's in www/../gitmal)
git clone --no-hardlinks --bare $SRCDIR/../gitmal root/usr/local/www/git/gitmal.git
git -C root/usr/local/www/git/gitmal.git remote remove origin
git -C root/usr/local/www/git/gitmal.git update-server-info

# generate static site
pushd root/usr/local/www/git/gitmal.git
~/go/bin/gitmal --minify .
mv output ../gitmal
popd

# generate the etags
pushd root/usr/local/www/git/
generate_etags "/git"
popd

# compress the files
find root/usr/local/www -type f -exec $SRCDIR/scripts/compress.sh \{\} \;

# copy in cgi-bin last so it doesn't get compressed
cp -r $SRCDIR/cgi-bin root/usr/local/www/
