#!/bin/sh

set -x
usage() {
    echo "$0 directory"
    exit 1
}

die() {
    echo "$1"
    exit 1
}

testsite=0
if [ "$1" = "-t" ]
then
    testsite=1
    shift
fi

DIR=$(basename $1)
DESTFILENAME=$2
if test -f /bsd # OpenBSD
then
    CURINODE=$(stat -f "%i" current/metadata.sh)
    if [ "$testsite" -eq 0 ] && [ "$(stat -f '%i' $DIR/metadata.sh)" -eq "$CURINODE" ]
    then
        DEST=dev
    else
        DEST=public
    fi
else # assuming linux
    CURINODE=$(stat --format="%i" current/metadata.sh)
    if [ "$testsite" -eq 0 ] && [ "$(stat --format="%i" $DIR/metadata.sh)" -eq "$CURINODE" ]
    then
        DEST=dev
    else
        DEST=public
    fi
fi

LNSFX=""
if [ -n "$LN" ]; then
    LNSFX="${LN}_"
fi

test -d "$DIR" || usage
test -d ../public/ || die "You must run this from openbsd-webzine/current"
ls $DIR/${LNSFX}*.html 2>&1 >/dev/null || die "no ${LN} html file in $DIR"

. ./${DIR}/metadata.sh

if test -z "$DESTFILENAME"
then
    DESTFILENAME="../${DEST}/${LNSFX}${DIR}.html"
fi

if [ -n "${LNSFX}" ]; then
	cat _common/header $DIR/${LNSFX}*html _common/footer > $DESTFILENAME
else
	cat _common/header \
		$(ls $DIR/*html | grep "/.*[0-9]_") \
		_common/footer > $DESTFILENAME
fi

if echo $DIR | grep issue
then
    set -e
    # replace with issue number
    issue="${1#issue-}"
    sed -i "s/__ISSUE__/${issue}/g" $DESTFILENAME
    sed -i "s/__TITLE__/issue #${issue}/g" $DESTFILENAME
    sed -i "s/__FILENAME__/issue-${issue}.html/" $DESTFILENAME
    # replace date
    if test -f /bsd # on OpenBSD
    then
        DATETIME="$(date -j -f "%Y-%m-%dT%H:%M:%SZ" "${PUBLISHED_DATE}" +"%Y-%m-%d %H:%M")"
        HUMAN_DATE="$(date -j -f "%Y-%m-%dT%H:%M:%SZ" "${PUBLISHED_DATE}" +"%B %e, %Y")"
    else # assuming Linux
        DATETIME="$(env LC_TIME=C TZ=UTC date --date="${PUBLISHED_DATE}" "+%Y-%m-%d %H:%M")"
        HUMAN_DATE="$(env LC_TIME=C TZ=UTC date --date="${PUBLISHED_DATE}" "+%B %e, %Y")"
    fi

    if [ $? -ne 0 ];
    then
        echo "err: Please fill ${DIR}/metadata.sh with ISO-8601 valid date"
        exit 1
    fi
    sed -i "s,__DATETIME__,${DATETIME}," $DESTFILENAME
    sed -i "s/__HUMAN_DATE__/${HUMAN_DATE}/" $DESTFILENAME
else
    # index.html changes
    sed -i "s/ #__ISSUE__//g" $DESTFILENAME
    sed -i "s/__TITLE__/homepage/g" $DESTFILENAME
    sed -i "s/__FILENAME__/${LNSFX}index.html/" $DESTFILENAME
fi

