#!/bin/bash
# mkwheels — build a reproducible, pinned Python wheels tarball for a package.
#
# Copyright (C) 2026 Danilo M. <danix@danix.xyz>
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 2 as published by
# the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, see <https://www.gnu.org/licenses/>.
set -eu

usage() {
    cat <<EOF
usage: ${0##*/} <pkg> <ver> [epoch]

Build a reproducible pinned Python wheels tarball <pkg>-wheels-<ver>.tar.gz
plus a hashed requirements.txt, for vendoring into a SlackBuild.

  <pkg> <ver>  PyPI package name and exact version to vendor.
  [epoch]      SOURCE_DATE_EPOCH for the tarball mtime. Omitted -> auto-derived
               from the PyPI release upload time (a warning is printed).

  OUTPUT       env var: output directory (default: current dir).

Requires: python3+pip, jq, curl, tar, gzip, md5sum.
EOF
}

case "${1:-}" in
    -h|--help) usage; exit 0 ;;
esac
[ $# -ge 2 ] && [ $# -le 3 ] || { usage >&2; exit 2; }

pkg=$1
ver=$2
epoch=${3:-}
OUTPUT=${OUTPUT:-$PWD}

# Check required tools up front.
for tool in python3 jq curl tar gzip md5sum; do
    command -v "$tool" >/dev/null 2>&1 || {
        echo "error: required tool not found: $tool" >&2
        exit 1
    }
done
python3 -m pip --version >/dev/null 2>&1 || {
    echo "error: python3 pip module not available" >&2
    exit 1
}

echo "mkwheels: $pkg $ver -> $OUTPUT/$pkg-wheels-$ver.tar.gz"

# Resolve SOURCE_DATE_EPOCH. Explicit arg wins; otherwise derive it from the
# earliest file upload time of this version on PyPI (a real, reproducible,
# release-tied timestamp).
if [ -z "$epoch" ]; then
    meta=$(curl -fsSL "https://pypi.org/pypi/$pkg/$ver/json") || {
        echo "error: cannot fetch PyPI metadata for $pkg $ver" >&2
        exit 1
    }
    iso=$(printf '%s' "$meta" \
        | jq -r '[.urls[].upload_time_iso_8601] | sort | .[0] // empty')
    [ -n "$iso" ] || {
        echo "error: no upload time found for $pkg $ver on PyPI" >&2
        exit 1
    }
    epoch=$(date -u -d "$iso" +%s)
    echo "warning: epoch not given; using PyPI upload time $iso (epoch $epoch)" >&2
fi
export SOURCE_DATE_EPOCH="$epoch"
