#!/bin/sh
set -o errexit
set -o nounset

if [ "$#" != '0' ]
then
  cat 1>&2 <<EOF
Usage: $0

Downloads the version corresponding to the spec file and creates a filtered
crate source. Run rust2rpm first.
EOF
  exit 1
fi

OUTDIR="${PWD}"
TMPDIR="$(mktemp --directory)"
trap "rm --recursive --force '${TMPDIR}'" INT TERM EXIT

CRATE='utf_types'
COMPAT=''
SPEC="rust-${CRATE}${COMPAT}.spec"
cd "$(dirname "${0}")"
VERSION="$(rpmspec --query "${SPEC}" --srpm --queryformat "%{version}")"
cd "${OUTDIR}"

cd "${TMPDIR}"
ARCHIVE="${CRATE}-${VERSION}.crate"
URL="https://crates.io/api/v1/crates/${CRATE}/${VERSION}/download"
echo "--> Downloading: ${URL}" 1>&2
curl --location --output="${ARCHIVE}" "${URL}"

echo "--> Extracting: $(basename "${ARCHIVE}")" 1>&2
tar --extract --gzip --file="${ARCHIVE}"
echo '--> Removing test code that seems to be CC0-1.0-licensed' 1>&2
TARDIR="${CRATE}-${VERSION}"
MTIME="$(stat --format='%Y' "${TARDIR}")"
cd "${TARDIR}"
for s in src/*.rs
do
  awk '/Any copyright to the test code below this comment/ { x=1 }; !x' \
      "${s}" > "${s}.filtered"
  touch -r "${s}" "${s}.filtered"
  mv "${s}.filtered" "${s}"
done
cd - >/dev/null
# Make sure the original mtime is preserved even if we modified the base
# directory by removing something at the top level. (So far, we didn’t.)
touch --date="@${MTIME}" "${TARDIR}"
FILTERED="${CRATE}-${VERSION}-clean.crate"
echo "--> Re-archiving: ${FILTERED}" 1>&2
# https://www.gnu.org/software/tar/manual/html_section/Reproducibility.html
TZ=UTC LC_ALL=C tar \
    --create \
    --sort=name \
    --format=posix \
    --numeric-owner --owner=0 --group=0 \
    --mode=go+u,go-w \
    --pax-option='delete=atime,delete=ctime' \
    "${TARDIR}/" |
  pigz -11 > "${FILTERED}"
mv --verbose "${FILTERED}" "${OUTDIR}"
echo 'Done.' 1>&2
