#!/bin/sh
set -e

if [ ! $# = 1 ]; then
    printf >&2 "Usage: %s <path> [ext]\n" "$(basename "$0")"
    exit 0
fi

_path="$1"
ext="${2:-md}"

if [ ! -d "$_path" ]; then
    printf >&2 "error: path %s not found\n" "$_path"
    exit 1
fi

find "$_path" -type f -name "*.$ext" | sort -r | while read -r file; do
    post=$file
    # skip indices
    if [[ "$post" == *index.md ]]; then continue; fi

    postdate=$("$ZS" vars "$post" postdate)
    if [ -z "$postdate" ]; then
      inputdate=$(basename $file | cut -d- -f1-3)
      postdate=$(date -j -f "%Y-%m-%d" "$inputdate" || true)
    fi

		url=$("$ZS" vars "$post" url)

		title=$("$ZS" vars "$post" title | tr A-Z a-z)
		if [ -z "$title" ]; then
		  title=$(basename $file | cut -d- -f4-)
	  fi

	  #post=$(ZS_LAYOUT=include $ZS build $file)

		echo "<entry>"
    echo "  <title>$title</title>" 
    echo "  <link href=https://jonathan.is/$url />"
    echo "  <updated>$postdate</updated>"
    echo "  <id>https://jonathan.is/$url</id>"
    echo "  <content type=html>$post</content>"
    echo "</entry>"
done