#!/bin/sh

set -e      # fail on errors
set -u      # fail on usage of unbound variables

PKG="bgoffice-computer-terms"
ODT="en-bg-comp-dict.odt"
SITE="http://m-balabanov.hit.bg"

TMP=`mktemp -d`

trap "rm -rf $TMP" EXIT QUIT TERM

wget -O "$TMP/$ODT" "$SITE/$ODT"

STAMP=`odt2txt "$TMP/$ODT" \
    | grep "Последно обновяване" \
    | sed -e 's/^ *Последно обновяване: \([0-9]\+\).\([0-9]\+\).\([0-9]\+\) г., \([0-9]\+\):\([0-9]\+\) ч./\3 \2 \1 \4 \5/'`

YR=`echo "$STAMP" | cut -f1 -d" " | sed s/^0//`
MO=`echo "$STAMP" | cut -f2 -d" " | sed s/^0//`
DA=`echo "$STAMP" | cut -f3 -d" " | sed s/^0//`
HR=`echo "$STAMP" | cut -f4 -d" " | sed s/^0//`
MI=`echo "$STAMP" | cut -f5 -d" " | sed s/^0//`

if [ -z "$YR" ] || [ -z "$MO" ] || [ -z "$DA" ] || [ -z "$HR" ] || [ -z "$MI" ];
then
    echo "Unable to parse last change timestamp ($STAMP)"
    exit 1
fi

STAMP=`printf "%d%02d%02d%02d%02d" "$YR" "$MO" "$DA" "$HR" "$MI"`

if ! echo "$STAMP" | egrep -q '^[0-9]+$'; then
    echo "Invalid version stamp [$STAMP]"
    exit 1
fi

VER="0.0.$STAMP"

mkdir "$TMP/$PKG-$VER.orig"
mv "$TMP/$ODT" "$TMP/$PKG-$VER.orig/"

tar czf "../${PKG}_$VER.orig.tar.gz" -C "$TMP" "$PKG-$VER.orig"
mv "$TMP/$PKG-$VER.orig/$ODT" .

echo "../${PKG}_$VER.orig.tar.gz ready"
