#! /bin/bash

set -eu
shopt -s nullglob

TMP=tmp
RFC=$TMP/usr/share/doc/RFC

rm -rf $RFC
mkdir -p $RFC/queue
mkdir -p $RFC/links
ln -f $( sed -e 's,^,../extra/,' rfc-queue.txt | grep -v '\[missing]' ) \
    $RFC/queue

echo "- $(date) linking RFCs into the debian/tmp directory"
perl makelinks.pl $RFC
# Fix extra files whose indices are not numeric.
ln -f ../rfc17a.* $RFC/unclassified
ln -f ../rfc1131-original.pdf $RFC/old/proposed-standard

echo "- $(date) linking extra files"
ln -f $(echo ../extra/{rfc-*.html,queue.html,rfcxx00.*} rfc-*.txt ../rfc-index.txt) \
    $RFC

find ../ ../extra/ -maxdepth 1 -type f -links 1 \! -name '*.ps' > unused-files

echo "- $(date) compressing..."
find $RFC -type f -size +4k -print0 > files-to-compress
# Ensure rfc-queue is compressed, even if < 4k.
if ! grep rfc-queue.txt files-to-compress; then
    find $RFC -type f -name rfc-queue.txt -print0 \
         >> files-to-compress
fi
# Try to parallel compress things, if allowed. The 64 max argument
# limit is arbitrary, currently there are about 17K files, so this
# will result in ~260 gzip invocations.
if [[ -z "$NUMJOBS" ]]; then
  NUMJOBS=1
fi
cat files-to-compress | xargs -0 -P"$NUMJOBS" -n64 gzip --best -n -r -f
echo "- $(date) finished compressing"

echo "- $(date) fix file permissions"
chmod -R a-wx,a+rX,u+w $RFC
