#!/usr/bin/env nix-shell
#!nix-shell --pure -i bash -p wget -p gnupg -p cacert -p nix

# Update patch set for GNU Bash or Readline.

if [ $# -ne 2 ]
then
    echo "Usage: $(basename "$0") PROJECT VERSION"
    echo ""
    echo "Update the patch set for PROJECT (one of \`bash' or \`readline') for"
    echo "the given version (e.g., \`4.0').  Produce \`PROJECT-patches.nix'."
    exit 1
fi

PROJECT="$1"
VERSION="$2"
DIR=$(dirname "$0")
VERSION_CONDENSED="$(echo "$VERSION" | sed -es/\\.//g)"
PATCH_LIST="$DIR/$PROJECT-$VERSION-patches.nix"

set -e

rm -vf "$PATCH_LIST"

# https://savannah.gnu.org/projects/bash/: Group Admins: Chet Ramey
# https://savannah.gnu.org/users/chet: Download GPG Key
wget "https://savannah.gnu.org/people/viewgpg.php?user_id=2590" -O gpgkey.asc
echo "db4041b4d3896b9f21250e6c29861958bd5d4781f521f06beda849a9ed79fae8  gpgkey.asc" > gpgkey.asc.sha256
sha256sum -c gpgkey.asc.sha256
gpg --import ./gpgkey.asc
rm gpgkey.asc{,.sha256}

( echo "# Automatically generated by \`$(basename "$0")'; do not edit." ;	\
  echo "" ;								\
  echo "patch: [" )							\
>> "$PATCH_LIST"

for i in {001..100}
do
    wget -P "$DIR" "ftp.gnu.org/gnu/$PROJECT/$PROJECT-$VERSION-patches/$PROJECT$VERSION_CONDENSED-$i" || break
    wget -P "$DIR" "ftp.gnu.org/gnu/$PROJECT/$PROJECT-$VERSION-patches/$PROJECT$VERSION_CONDENSED-$i.sig"
    gpg --verify "$DIR/$PROJECT$VERSION_CONDENSED-$i.sig"
    hash=$(nix-hash --flat --type sha256 --base32 "$DIR/$PROJECT$VERSION_CONDENSED-$i")
    echo "  (patch \"$i\" \"$hash\")"	\
    >> "$PATCH_LIST"

    rm -f "$DIR/$PROJECT$VERSION_CONDENSED-$i"{,.sig}
done

echo "]" >> "$PATCH_LIST"

# bash interprets numbers starting with 0 as octals
echo "Got $((10#$i - 1)) patches."
echo "Patch list has been written to \`$PATCH_LIST'."
