#!/bin/bash

set -e

# Run the original quickbook first
@QUICKBOOK@ $@

# And if it fails, exit
if [[ $? -ne 0 ]] ; then
	exit $?
fi

# Now try to find out what was written
for i in "$@"; do
  key="$i"
  case $key in
	--output-file=*)
      OUTPUTFILE="${i#*=}"
      shift # past argument=value
	  ;;
    --output-file)
      OUTPUTFILE="$2"
      shift # past argument
      shift # past value
      ;;
    *)    # unknown option
      shift # past argument
      ;;
  esac
done

if [[ "x$OUTPUTFILE" != "x" && "x$SOURCE_DATE_EPOCH" != "x" ]] ; then
	BUILD_DATE="$(date --utc --date="@${SOURCE_DATE_EPOCH:-$(date +%s)}" +'%Y-%m-%d %H:%M:%S')"
	sed -i -e "s/\$Date:.\\+\\$/$BUILD_DATE/g" $OUTPUTFILE
fi
