#!/usr/bin/env bash

set -Eeuo pipefail

filter=${1:-.}

gen () {
    f="$(mktemp)"
    # shellcheck disable=SC2064
    trap "rm -f $f" EXIT
    if grep -q "$filter" <<< "$1"; then
        echo "Generating $1..."
        echo "# Generated by $0" > "$f"
        cabal2nix "$2" >> "$f" "${@:3}"
        mv "$f" "${1}.nix"
    else
        echo "Skipping $1..."
    fi
}

cd "$(dirname "$0")"

gen stackage-server --hpack ../.

# Has my R2 patch, which is still unreleased on 2025-01-24
amazonka_version=a7d699be1076e2aad05a1930ca3937ffea954ad8

2>/dev/null gen amazonka-core "https://github.com/brendanhay/amazonka/archive/${amazonka_version}.zip" --subpath lib/amazonka-core
gen amazonka-s3 "https://github.com/brendanhay/amazonka/archive/${amazonka_version}.zip" --subpath lib/services/amazonka-s3

# Pinned to 5.0.18.4 to avoid accidentally regenerating hoogle files. See
# warning in stack.yaml!
gen hoogle cabal://hoogle-5.0.18.4

# FIXME: I don't remember why this had to be patched.
gen pantry https://github.com/commercialhaskell/pantry/archive/5df643cc1deb561d9c52a9cb6f593aba2bc4c08e.zip

echo "Success!"
