#!/usr/bin/env nix-shell
#!nix-shell -i bash -p cabal2nix curl jq nix-update nixfmt

set -euo pipefail

# This is the directory of this update.sh script.
script_dir="$(dirname "${BASH_SOURCE[0]}")"

backend_derivation_file="${script_dir}/generated-backend-package.nix"

latest_version="$(curl --silent 'https://api.github.com/repos/gren-lang/compiler/releases/latest' | jq --raw-output '.tag_name')"

echo "Updating gren backend to version ${latest_version}."
echo "Running cabal2nix and outputting to ${backend_derivation_file}..."

cat > "${backend_derivation_file}" << EOF
# This file has been autogenerated with cabal2nix.
# Update via ./update.sh
EOF

cabal2nix 'https://github.com/gren-lang/compiler.git' --revision "${latest_version}" --jailbreak >> "${backend_derivation_file}"
nixfmt "${backend_derivation_file}"

echo 'Finished backend generation.'

echo "Updating frontend to version ${latest_version}"

nix-update gren --version "${latest_version}"
