#!/usr/bin/env bash

set -euxo pipefail

DEFAULT_STORE=$HOME/.cabal
STORE_DIR="${1:-$DEFAULT_STORE}"

# README!
# Every time you modify the `stack.yaml` and as result the relevant `cabal.project`
# changes, you have to make sure to update the `expected_cabal_project_hash` and
# `expected_cabal_project_freeze_hash` with the
# `sha256sum` result calculated on the `cabal.project` and `cabal.project.freeze`.
# This ensures the files stay deterministic so that CI cache can kick in.
expected_cabal_project_hash="3c1002c8ed7be226b2e189fdb7debef5b3c43d0f56e44df73d500954074c4568"
expected_cabal_project_freeze_hash="2d3704d107bd8d08056ce4f0eb1f42202cb7f49a67c62a2445a6c70c7235f861"

cabal --store-dir=$STORE_DIR v2-update 'hackage.haskell.org,2023-06-24T21:28:46Z'

# Install stack2cabal if it can't be found.
if ! stack2cabal --help &> /dev/null
then
    echo "stack2cabal could not be found"
    cabal --store-dir=$STORE_DIR v2-install --index-state="2023-06-24T21:28:46Z" stack2cabal-1.0.14 --overwrite-policy=always
fi
stack2cabal --no-run-hpack -p '2023-06-24 21:28:46'

actual_cabal_project_hash=$(sha256sum cabal.project | awk '{printf "%s",$1}')
actual_cabal_project_freeze_hash=$(sha256sum cabal.project.freeze | awk '{printf "%s",$1}')
if [[ $actual_cabal_project_hash != $expected_cabal_project_hash ]]; then
  echo "ERROR! hash mismatch between expected cabal.project and the one computed by stack2cabal."
  exit 1
else
  echo "cabal.project updated successfully."
fi
if [[ $actual_cabal_project_freeze_hash != $expected_cabal_project_freeze_hash ]]; then
  echo "ERROR! hash mismatch between expected cabal.project.freeze and the one computed by stack2cabal."
  exit 1
else
  echo "cabal.project.freeze updated successfully."
fi