#!/bin/sh
set -e

# The file /var/lib/texmf/web2c/updmap.log contains timestamps for the files that it just generated
# Not reported yet. See https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=XXXXXXX

# Don't run if texlive-base is not installed
if [ ! -e /usr/bin/updmap ];
then
  exit 0
fi

# Don't run if the script has been fixed
if grep -q gmtime /usr/share/texlive/texmf-dist/scripts/texlive/updmap.pl;
then
  exit 0
fi

# Change: printf LOG "%s\n\n", scalar localtime();
# To    : printf LOG "%s\n\n", defined $ENV{SOURCE_DATE_EPOCH} ? scalar gmtime($ENV{SOURCE_DATE_EPOCH}) : scalar localtime();
sed -i -e "/scalar localtime/s/scalar localtime/defined \$ENV{SOURCE_DATE_EPOCH} ? scalar gmtime(\$ENV{SOURCE_DATE_EPOCH}) : scalar localtime/" /usr/share/texlive/texmf-dist/scripts/texlive/updmap.pl

# Change: my ($s,$m,$h,$D,$M,$Y)=localtime($stat[9]);
# To    : my ($s,$m,$h,$D,$M,$Y)=defined $ENV{SOURCE_DATE_EPOCH} ? gmtime($ENV{SOURCE_DATE_EPOCH}) : localtime($stat[9]);
sed -i -e "/localtime([$]/s/localtime/defined \$ENV{SOURCE_DATE_EPOCH} ? gmtime(\$ENV{SOURCE_DATE_EPOCH}) : localtime/" /usr/share/texlive/texmf-dist/scripts/texlive/updmap.pl

# The timestamp of the files that are generated by the script will be corrected in the 'lb binary' phase
updmap -sys

echo "P: $(basename $0) Reproducible hook has been applied"
