#!/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.
#
# Also fetches the latest types-psutil and types-setuptools stubs. They are
# only needed while building, for the mypyc compilation.

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

fetch_sdist() {
  local url sha256 file

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

  if [ -z "$file" ]; then
    echo "No sdist found for $1 $2!"
    return 1
  fi

  rm -f ${file%%-*}-*.tar.?z

  wget "$url" || return 1
  echo "$sha256  $file" | sha256sum -c - || return 1

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

fetch_sdist $PYPI_NAME $VERSION || exit 1

for stubs in types-psutil types-setuptools; do
  fetch_sdist $stubs $(curl -fsSL "https://pypi.org/pypi/$stubs/json" | jq -r '.info.version') || exit 1
done
