#!/usr/bin/env bash

set -euxo pipefail

current_dir=$(basename "$PWD")

if [ "$current_dir" == "bin" ]; then
    source ./setup-ci-environment
    ./install-cabal2stack
else
    source ./bin/setup-ci-environment
    ./bin/install-cabal2stack
fi

# README!
# Every time you modify the `cabal.project`, 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="c9fe39301e8b60bfd183e60e7e25a14cd1c9c66d8739bf9041ca3f4db89db7c6"
expected_cabal_project_freeze_hash="2c8960ffcf1b94aa11a3543e3b5facd2db5af19569fecaec4bc0ab4c1edd22a5"

cabal --store-dir=$STORE_DIR v2-build --dry-run
cabal2stack --system-ghc --allow-newer --resolver lts-21.17 --resolver-file devops/stack/lts-21.17.yaml -o stack.yaml
cabal --store-dir=$STORE_DIR v2-freeze

# Run 'sed' to remove the constraint for 'gargantext', as it doesn't make sense and
# for the test we need to run this with a different flag.
echo -e "\e[33mPatching cabal.project.freeze to remove redundant constraint on gargantext\e[0m"
sed -i '/^ *gargantext/d' cabal.project.freeze

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 -e "\e[31mERROR! hash mismatch between expected cabal.project and the one computed by cabal2stack.\e[0m"
  echo -e "\e[33mPlease update the hashes inside the './bin/update-project-dependencies' file.\e[0m"
  exit 1
else
  echo -e "\e[32mstack.yaml updated successfully.\e[0m"
fi
if [[ $actual_cabal_project_freeze_hash != $expected_cabal_project_freeze_hash ]]; then
  echo -e "\e[31mERROR! hash mismatch between expected cabal.project.freeze and the one computed by cabal2stack.\e[0m"
  echo -e "\e[33mPlease update the hashes inside the './bin/update-project-dependencies' file.\e[0m"
  exit 1
else
  echo -e "\e[32mcabal.project.freeze updated successfully.\e[0m"
fi
