#!/bin/bash

# Fetch the sdist from PyPI, check it against PyPI's SHA256 and repack it
# as .tar.lz. Without an argument, fetches the latest release.

PYPI_NAME=ast-serialize
VERSION=${1:-$(curl -fsSL "https://pypi.org/pypi/$PYPI_NAME/json" | jq -r '.info.version')}

read -r URL SHA256 FILE < <(curl -fsSL "https://pypi.org/pypi/$PYPI_NAME/$VERSION/json" \
  | jq -r '.urls[] | select(.packagetype == "sdist") | "\(.url) \(.digests.sha256) \(.filename)"')

if [ -z "$FILE" ]; then
  echo "No sdist found for $PYPI_NAME $VERSION!"
  exit 1
fi

rm -f ${FILE%%-*}-*.tar.?z
rm -rf cargo-${FILE%%-*}-* cargo-config-${FILE%%-*}-*.toml

wget "$URL" || exit 1
echo "$SHA256  $FILE" | sha256sum -c - || exit 1

SRCDIR=${FILE%.tar.gz}
tar xf $FILE || exit 1

cd $SRCDIR
  # cargo prints the source config these vendored crates need (git
  # dependencies included) on stdout. Keep it for the SlackBuild.
  if ! [ -f /usr/bin/cargo-vendor-filterer ]; then
    echo "WARNING: Creating unfiltered vendor libs tarball!"
    cargo vendor vendor > ../cargo-config-$SRCDIR.toml || exit 1
  else
    cargo vendor-filterer --platform="x86_64-unknown-linux-gnu" --platform="i686-unknown-linux-gnu" vendor > ../cargo-config-$SRCDIR.toml || exit 1
  fi
  mv vendor ../cargo-$SRCDIR
cd ..

tar cf cargo-$SRCDIR.tar cargo-$SRCDIR
plzip -9 cargo-$SRCDIR.tar
rm -rf $SRCDIR cargo-$SRCDIR

gunzip "$FILE"
plzip -9 "${FILE%.gz}"
