#! /bin/bash

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

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

echo "- $(date) linking RFCs"
perl makelinks.pl $RFC
# what were they smoking?!
ln -i ../rfc17a.* $RFC/unclassified 2>>ln-failed.log

echo "- $(date) rewriting broken PostScript files"
for f in rfc1247.ps \
         rfc1275.ps rfc1276.ps rfc1277.ps rfc1278.ps rfc1279.ps \
         rfc1583.ps rfc1896.ps; do
  src="$(find $RFC -type f -name $f)"
  test -f "$src" || { echo Cannot find file $f? 1>&2; exit 1; }
  tmp="$(mktemp "${src}.XXXXXX")" || exit 1
  trap "rm -f '$tmp'" EXIT
  ps2ps "$src" "$tmp"
  mv -f "$tmp" "$src"
  trap - EXIT
done

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

find .. -links 1 > 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
# don't work on a dir find is running on
cat files-to-compress | xargs -0 gzip --best -n -r -f
echo "- $(date) finished compressing"

chmod -R a-wx,a+rX,u+w $RFC
