#!/usr/bin/env bash
set -eux
set -o pipefail
githubToken=$(pass julm/github.com/token/nixpkgs-patches.sh)
{
echo '['
for pr in \
  83904 \
  93305_ \
  93293_ \
  93457_ \
  93659 \
  93629 \
  94938 \
  96655 \
  97740 \
  98455 \
  98734 \
  101071 \
  104457 \
  104460 \
  ; do
  PR=${pr%_}
  test $PR = $pr || echo '/*'
  # pkgs.fetchpatch tries to normalize the patch using filterdiff after downloading it
  # https://github.com/NixOS/nixpkgs/issues/41401#issuecomment-394173658
  nix=$(mktemp)
  trap "rm $nix" EXIT
  cat >"$nix" <<EOF
    { pkgs ? import <nixpkgs> {} }:
    pkgs.fetchpatch {
      url =  "https://github.com/NixOS/nixpkgs/pull/$PR.diff";
      sha256 = "0000000000000000000000000000000000000000000000000000";
    }
EOF
  hash=$(nix build -f "$nix" |& sed -ne 's/^ *got: *//p')
  # Token generated on https://github.com/settings/tokens
  info=$(curl -Ls -H "Authorization: token $githubToken" \
    https://api.github.com/repos/NixOS/nixpkgs/pulls/$PR)
  description=$(printf %s "$info" | jq --raw-output .title)
  cat <<EOF
{$(test "$(printf %s "$info" | jq --raw-output .merged)" = false || echo " # merged")
  meta.description = "$description";
  url = "https://github.com/NixOS/nixpkgs/pull/$PR.diff";
  sha256 = "$hash";
}
EOF
  test $PR = $pr || echo '*/'
done
echo ']'
} >"${0%.sh}".nix