#!/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

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

function check(){
    local rc=0
    sed -rn 's|^.*\!\[.*\]\(%assets_url%/(.*)\)$|\1|p' $1 | while read line
    do
        if [ ! -f "$BASEDIR/$ASSETS_DIR/$line" ]
        then
            echo "`basename $1`: $line not found" >&2
            rc=1
        fi
    done
    return $rc
}

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

exit $rc
