#!/usr/bin/env sh

# Site specific settings
DOMAIN="https://iiogama.0x212.com"
TITLE="Just some dude creating things"
DESCRIPTION="iiogama@0x212.com"
COPYRIGHT="Copyright $(date +%Y), Thai Noodles"
AUTHOR="Thai Noodles, (iiogama@0x212.com)"
HTML_LANG="en_US" # Your document (HTML) language setting
CONTENT_DIR="content"
BLOG_DIR="blog"
ASSET_DIR="assets"
OUTPUT_DIR="_output"
FEED_FILE="index.xml"
TIME="01:00:00 PST"
TTL="60"

function build_pages() {
	rsync -r --exclude="*.html" "$CONTENT_DIR/" "$OUTPUT_DIR/"
	rsync -r "$ASSET_DIR/" "$OUTPUT_DIR/"
	find $CONTENT_DIR -type f -name "*.html" | while read file; do
		PAGE_FILE="$(echo "$file" | sed "s/$CONTENT_DIR/$OUTPUT_DIR/")"
		echo '<!DOCTYPE html>' >> "$PAGE_FILE"
		echo '<html xmlns="http://www.w3.org/1999/xhtml" lang="en_US" xml:lang="en_US">' >> "$PAGE_FILE"
		cat "templates/_head.html" >> "$PAGE_FILE"
		echo '<body>' >> "$PAGE_FILE"
		cat "templates/_nav.html" "$file" "templates/_footer.html" >> "$PAGE_FILE"
		echo '</body>' >> "$PAGE_FILE"
		echo '</html>' >> "$PAGE_FILE"
	done
}

function build_feed() {
	echo "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>
	<?xml-stylesheet href=\"style.xsl\" type=\"text/xsl\"?>
	<rss version=\"2.0\">
	<channel>
		<title>$TITLE</title>
		<link>$DOMAIN</link>
		<description>$DESCRIPTION</description>
		<copyright>$COPYRIGHT</copyright>
		<ttl>$TTL</ttl>" >> "$OUTPUT_DIR/$FEED_FILE"
	find $OUTPUT_DIR/$BLOG_DIR -type f -name "*.html" | while read file; do
		POST_DATE="$(date -d "$(sed -n 's|^<p class="date">\([^<]*\)</p>$|\1|p' $file)" +"%a, %d %b %Y %H:%M:%S")"
		CAT_DATE="$(date -d "$(sed -n 's|^<p class="date">\([^<]*\)</p>$|\1|p' $file)" +"%Y/%m/%d/%u")"
		POST_TITLE="$(sed -n 's|^<h1 class="title">\([^<]*\)</h1>$|\1|p' $file)"
		POST_CONTENT="$(sed -n '/<article>/,/<\/article>/p' $file | sed -e '1s/.*<article>//' -e '$s/<\/article>.*//')"
		echo "
		<item>
			<pubDate>$POST_DATE PST</pubDate>
			<category>$CAT_DATE</category>
			<title>$POST_TITLE</title>
			<link>$DOMAIN/$BLOG_DIR$(basename ${file})</link>
			<description><![CDATA[$POST_CONTENT]]></description>
			<author>$AUTHOR</author>
			<guid>$DOMAIN/$BLOG_DIR$(basename ${file})</guid>
		</item>" >> "$OUTPUT_DIR/$FEED_FILE"
	done
	echo "</channel>
	</rss>" >> "$OUTPUT_DIR/$FEED_FILE"
	xsltproc "$OUTPUT_DIR/$FEED_FILE" > "$OUTPUT_DIR/$BLOG_DIR/index.html"
}

case "$1" in
	build)
		build_pages
		build_feed
		;;
esac
