#!/bin/sh
set -eux

DIST_ARCHIVES="$1"
VERSION="$2"
PACKAGE="$3"
BIN="${4:-}"

if [ "$BIN" != --bin ]; then
  # Assert version
  if git rev-parse "$VERSION" > /dev/null; then
    echo "Tar $VERSION already exists, exitting."
    exit 2
  fi

  # Update NEWS
  sed -i "s/^\* Unreleased$$/* $VERSION - $(date -I)/" NEWS
  cat <<EOF | cat - NEWS | sponge NEWS
* Unreleased
** Added
** Changed
** Deprecated
** Removed
** Fixed
** Security
EOF
  vi NEWS
  git diff NEWS
  set +x
  printf 'Is the above NEWS diff acceptable? Press CTRL+c to cancel.'
  read -r _
  set -x
  git add NEWS
  git commit -m "Update NEWS: release version $VERSION."

  # Make release artifacts
  gpg --sign --armor --yes "$DIST_ARCHIVES"
  git tag "$VERSION"
  SHA_TAR="$(git hash-object -w "$DIST_ARCHIVES")"
  SHA_SIG="$(git hash-object -w "$DIST_ARCHIVES.asc")"
  git notes --ref=refs/notes/tarballs   add -f -C "$SHA_TAR" "$VERSION"
  git notes --ref=refs/notes/signatures add -f -C "$SHA_SIG" "$VERSION"
  NOTE=$(cat <<EOF
Get this release with:
  git cat-file -p $SHA_TAR > $DIST_ARCHIVES
  git cat-file -p $SHA_SIG > $DIST_ARCHIVES.asc
EOF
)
  git notes append -m "$NOTE"
  sed -i -e "s/blob?id=.*\"/blob?id=$(git notes --ref=refs/notes/tarballs list "$VERSION")\"/" "guix/channel/xyz/euandreh/$PACKAGE/channel.scm.in"
  sed -i -e "s/(base32 \".*\")/(base32 \"$(guix download "$DIST_ARCHIVES" | tail -n 1)\")/"    "guix/channel/xyz/euandreh/$PACKAGE/channel.scm.in"
  ./configure --enable-programmer-mode
  git add "guix/channel/xyz/euandreh/$PACKAGE/channel.scm" "guix/channel/xyz/euandreh/$PACKAGE/channel.scm.in"
  git commit -m "Update released version $VERSION in channel.scm.in file."

  # Publish release artifacts
  git push --tags
  git push origin refs/notes/tarballs
  git push origin refs/notes/signatures
  git push origin refs/notes/commits
  git push
else
  guix pull
  BINARY_TARBALL="$(guix pack -RR -S /bin=bin -S /etc=etc "$PACKAGE")"
  SHA_BIN="$(git hash-object -w "$BINARY_TARBALL")"
  git notes --ref=refs/notes/binaries add -f -C "$SHA_BIN" "$VERSION"
  NOTE=$(cat <<EOF
Pre-built universal binaries available with:
  git cat-file -p $SHA_BIN > $PACKAGE-bin.tar.gz
  tar xf $PACKAGE-bin.tar.gz
  bin/$PACKAGE
EOF
)
  git notes append -m "$NOTE"
  git push origin refs/notes/binaries
  git push origin refs/notes/commits
fi
