#!/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="18ab030988f53446ea717e1f4c7206fab10494d73c37108eebac78094fbf206b"
expected_cabal_project_freeze_hash="813bbd4fe878104d09b0f2afe46b3e4cef5a541fb1454b965836f2d7a0f0e99e"

cabal --store-dir=$STORE_DIR v2-update 'hackage.haskell.org,2023-12-10T10:34: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-12-10T10:34:46Z" --constraint 'Cabal==3.6.3.0' stack2cabal-1.0.14 --overwrite-policy=always
fi
stack2cabal --no-run-hpack -p '2023-11-23 20:05:40'

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
