#!/usr/bin/env bash

# init
if [ ! -d "output" ]; then
	echo "generating output directory..."
	mkdir -p output/{blog,media}
fi

# reset output directory
rm -rf output/*.html
rm -rf output/blog/*
cp template/style.css output/
cp content/robots.txt output/

# find pages
pages=$(find content/ -maxdepth 1 -name "*.md")
# find blog posts
blogPosts=$(find content/blog/ -name "*.md" | sort -r)

# generate:

# blog posts
echo "BlogList:" >> posts.yaml

for post in $blogPosts
do
	postFile=${post:19:-3}
	pandoc $post -o output/blog/$postFile.html --metadata-file=vars.yaml --template=template/article.html
	echo "  - link: $postFile" >> posts.yaml
	echo "    title: $(yq --front-matter=extract '.title' $post)" >> posts.yaml
	echo "    date: $(yq --front-matter=extract '.date' $post)" >> posts.yaml
done

# pages
for page in $pages
do
	# check if a page specific template exists
	if [ -f "template/${page:8:-3}.html" ]; then
		pageTemplate="${page:8:-3}.html"
	else
		pageTemplate="page.html"
	fi

	pandoc $page -o output/${page:8:-3}.html --metadata-file=vars.yaml --metadata-file=posts.yaml --template=template/$pageTemplate --highlight-style pygments
done

# rss
feed="<?xml version='1.0' encoding='UTF-8' ?>
<rss version='2.0'>
<channel>
 <title>wing's blog</title>
 <description>wing's blog</description>
 <link>$(yq '.url' vars.yaml)/blog</link>
 <lastBuildDate>$(date --utc '+%a, %d %b %Y %H:%M:%S UT')</lastBuildDate>"

for post in $blogPosts
do
	pubDate=$(yq --front-matter=extract '.date' $post)
	feed="$feed
	<item>
		<![CDATA[<title>$(yq --front-matter=extract '.title' $post)</title>]]>
		<description>$(yq --front-matter=extract '.description' $post)</description>
		<link>$(yq '.url' vars.yaml)/blog/${post:19:-3}</link>
		<pubDate>$(date --date=$pubDate '+%a, %d %b %Y 00:00:00 UT')</pubDate>
	</item>"
done

feed="$feed
</channel>
</rss>"

echo "$feed" > output/feed.xml

# generate card output
./card.curl > output/card

# tidy up and finish
rm posts.yaml

echo "site generated!"

# command line arguments
# serve the site with caddy for testing or upload to server
case $1 in

	serve)
		caddy run --config Caddyfile
		;;

	upload)
		# rsync
		rsync -av --delete output/ $(yq '.sshserver' vars.yaml):$(yq '.sshpath' vars.yaml)
		;;

esac
