#!/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=audioread
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

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

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