#!/bin/zsh

BLOG=$HOME/blog

Die() {
    echo >&2 "$1"
    exit 1
}

cd $BLOG
git rev-parse --git-dir &> /dev/null || Die "$BLOG is no git repo"

cd _posts || Die "No _posts dir"

if [[ ! -z "$1" && -d "$1" ]]; then
    DIR="$1"
else
    DIR=`mktemp -d /tmp/blog.XXXXXX`
fi

DATE=`date +%Y-%m-%d`
TIME=`date +%H:%M`

[[ ! -e "$DIR/post" ]] && (
    echo "---"
    echo "layout: post"
    echo "title: "
    echo "tags: []"
    echo "date: $DATE $TIME"
    echo "---"
    echo
) > "$DIR/post"

vim "$DIR/post" +3

echo "Your post is saved at $DIR/post"
echo -n "Press enter to publish post! "

read foo

# sanitize title - this assumes "title:"-header is on line three
TITLE=`sed -n '3{s/title: //;s/[^A-Za-z0-9_ -]//g;p}' $DIR/post | tr A-Z' ' a-z-`
POST="$BLOG/_posts/${DATE}-${TITLE}.markdown"

mv -v $DIR/post "$POST"
git add "$POST"
git commit -m "Blog post: $TITLE"
git push

echo -n "Cleaning up..."
rmdir -v $DIR
