#!/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='astral-html'
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 parse5 test fixtures due to licensing issues' 1>&2
TARDIR="${CRATE}-${VERSION}"
MTIME="$(stat --format='%Y' "${TARDIR}")"
rm --recursive --verbose --force "${TARDIR}/tests/fixtures/parse5"
# 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
