#!/bin/bash -efu

function print_usage_message_and_exit {
cat <<END >&$1
usage: $0 [--only-update-date|--help|-?]
    --only-update-date do not extend, but only update the last entry's date
    --help -?          print this help message
END
exit $(( $1 - 1 ))
}
readonly -f print_usage_message_and_exit

declare -i DO_EXTEND=1
if (($#)) && [[ "$1" = @(--help|-?) ]]; then
    print_usage_message_and_exit 1
elif (($#)) && [[ "$1" = @(--only-update-date) ]]; then
    DO_EXTEND=0
elif (($#)); then
    print_usage_message_and_exit 2
fi
readonly DO_EXTEND
readonly SCRIPT_DIR="$(dirname -- "$(realpath -e -- "$0")")"
readonly TOP_DIR="$(realpath -e -- "$SCRIPT_DIR/../..")"
readonly DEBIAN_DIR="$TOP_DIR/debian"
. "$TOP_DIR/build.conf"
readonly RDATE="$(date -uRd"$VERDATE $VERTIME")"

declare TEMP
if (($DO_EXTEND)); then
    TEMP="$(mktemp)"
    sed -r >"$TEMP" \
        -e "s/PARAMETER_VERSION/${VERSION}/g" \
        -e "s/PARAMETER_RDATE/${RDATE}/g" \
        -- "$SCRIPT_DIR/changelog.t"
    cat >>"$TEMP" -- "$DEBIAN_DIR/changelog"
    cat >"$DEBIAN_DIR/changelog" -- "$TEMP"
    rm -- "$TEMP"
else
    sed -r 's/^( -- (\S ?)*\S  )\S.*/\1'"${RDATE}"'/;ta;b;:a;n;ba;'\
     -i "$TOP_DIR/debian/changelog"
fi
exit 0

