#!/usr/bin/env nix-shell
#! nix-shell -i sh -p nix-prefetch-git jq

# shellcheck shell=sh

# print usage
if test -z "$1" || test "$1" = "-h"; then
  >&2 printf 'Usage: %s REV\n' "$0"
  >&2 printf 'Fetch and generate the Nix expression for the coreboot sources.\n'
  >&2 printf 'The result is written to stdout.\n\n'
  >&2 printf ' REV: \t revision of the coreboot git repository\n'
  exit 1
fi

# fetch coreboot source code
url=https://review.coreboot.org/coreboot.git
info=$(nix-prefetch-git "$url" "$1" --fetch-submodules)
coreboot=$(echo "$info" | jq .path -r)
hash=$(echo "$info" | jq .sha256 -r)

# extract version numbers and URLs
buildgcc="$coreboot/util/crossgcc/buildgcc"
# shellcheck disable=SC2046
export $(grep '^[A-Z]\+_VERSION=' "$buildgcc" | tail -n+2)
urls=$(awk -F'=|"' '/^[A-Z]+_ARCHIVE=/{print $3}' "$buildgcc")

# generate Nix expression
cat <<EOF
{ fetchurl }:
{ rev = "$1";
  sha256 = "$hash";
  toolchain = [
EOF

for url in $urls; do 
  # expand version inside the url
  url="$(eval echo "$url")"
  # prefetch to compute the hash
  hash=$(nix-prefetch-url --type sha256 "$url")

  cat <<EOF
    (fetchurl {
      url = "$url";
      sha256 = "$hash";
    })
EOF
done
printf "  ];\n}"
