#! /usr/bin/env nix-shell
#! nix-shell -i bash
#! nix-shell -p git -I nixpkgs=.
set -euo pipefail

filesToStage=(
  'pkgs/data/misc/hackage/pin.json'
  'pkgs/development/haskell-modules/configuration-hackage2nix/stackage.yaml'
  'pkgs/development/haskell-modules/hackage-packages.nix'
)

if ! git diff --quiet --cached; then
  echo "Please commit staged changes before running $0" >&2
  exit 100
fi

if ! git diff --quiet -- "${filesToStage[@]}"; then
  echo -n "Please commit your changes to the following files before running $0: " >&2
  echo    "${filesToStage[@]}" >&2
  exit 100
fi

stackage_diff="$(./maintainers/scripts/haskell/update-stackage.sh)"
hackage_diff="$(./maintainers/scripts/haskell/update-hackage.sh)"
readonly stackage_diff hackage_diff

# Prefer Stackage version diff in the commit header, fall back to Hackage
if [[ -n "$stackage_diff" ]]; then
  commit_message="haskellPackages: stackage $stackage_diff"
  if [[ -n "$hackage_diff" ]]; then
    commit_message="$commit_message

all-cabal-hashes: $hackage_diff"
  fi
elif [[ -n "$hackage_diff" ]]; then
  commit_message="haskellPackages: hackage $hackage_diff

all-cabal-hashes: $hackage_diff"
else
  echo "Neither Hackage nor Stackage changed. Nothing to do." >&2
  exit 0
fi

commit_message="$commit_message

(generated by maintainers/scripts/haskell/update-package-set.sh)"

# Using fast here because after the hackage-update eval errors will likely break the transitive dependencies check.
./maintainers/scripts/haskell/regenerate-hackage-packages.sh --fast

# A --do-commit flag probably doesn't make much sense
git add -- "${filesToStage[@]}"
git commit -m "$commit_message"
