#!/bin/bash

BASEDIR=`dirname $0`

if [ -f $BASEDIR/config.sh ]; then
    . $BASEDIR/config.sh
fi

if [ -z "$POSTS_DIR" ]
then
    echo "POSTS_DIR environment variable is unset." > /dev/stderr
    exit 2
fi

FIX=0

while getopts "f" option
do
    case $option in
        f)
            FIX=1
            ;;
    esac
done

shift $(($OPTIND - 1))

function check() {
    local rc=0
    post=$1
    title=`sed -n 's/^title: "\?\(.*\)"\?$/\1/p' $post` 
    safename=`echo $title | iconv -t ascii//TRANSLIT | tr '[:upper:]' '[:lower:]' | tr -s '[:punct:] ' '-' | sed 's/-*$//g;s/^-*//g'`
    if [ $post == $safename.md ]
    then
        rc=0
    else
        if [ $FIX -eq 1 ]
        then
            mv -v $post $safename.md
        else
            echo "$post should be named $safename.md" >&2
        fi
        rc=1
    fi
    return $rc
}

cd $BASEDIR/$POSTS_DIR
if [ -z "$1" ]
then
    rc=0
    for post in *
    do
        check $post
        if [ $? -ne 0 ]
        then
            rc=1
        fi
    done
else
    check $1
    rc=$?
fi

exit $rc
