#!/usr/bin/env bash
# Print the PyPI sdist URL and sha256 for a franklin-book release.
#
# Used to bump the Homebrew formula on every new release without
# fishing the values out of pypi.org by hand.
#
# Usage:
#   bin/bump-homebrew                # use latest PyPI release
#   bin/bump-homebrew 0.1.0          # use a specific version
#
# The output is ready to paste into Formula/franklin-book.rb:
#
#   url "https://files.pythonhosted.org/packages/source/f/franklin-book/franklin_book-0.1.0.tar.gz"
#   sha256 "<64 hex chars>"

set -euo pipefail

PKG="franklin-book"
VERSION="${1:-}"

if ! command -v curl >/dev/null; then
    echo "error: curl is required" >&2
    exit 1
fi
if ! command -v jq >/dev/null; then
    echo "error: jq is required (brew install jq)" >&2
    exit 1
fi

if [[ -z "$VERSION" ]]; then
    VERSION=$(
        curl -fsSL "https://pypi.org/pypi/${PKG}/json" |
            jq -r '.info.version'
    )
    echo "# resolved latest version: ${VERSION}" >&2
fi

META=$(curl -fsSL "https://pypi.org/pypi/${PKG}/${VERSION}/json")

SDIST_URL=$(
    echo "$META" |
        jq -r '.urls[] | select(.packagetype == "sdist") | .url'
)
SDIST_SHA=$(
    echo "$META" |
        jq -r '.urls[] | select(.packagetype == "sdist") | .digests.sha256'
)

if [[ -z "$SDIST_URL" || -z "$SDIST_SHA" ]]; then
    echo "error: no sdist found for ${PKG} ${VERSION} on PyPI" >&2
    echo "       (check https://pypi.org/project/${PKG}/${VERSION}/)" >&2
    exit 1
fi

cat <<EOF
  url "${SDIST_URL}"
  sha256 "${SDIST_SHA}"
EOF

echo >&2
echo "# next steps:" >&2
echo "#   1. paste the two lines above into Formula/franklin-book.rb" >&2
echo "#   2. brew update-python-resources Formula/franklin-book.rb" >&2
echo "#   3. brew audit --strict --new-formula franklin-book" >&2
echo "#   4. commit and push the tap repo" >&2
