#!/bin/sh
set -e

# Version from which to generate the changelog.
from=""

while [ $# -gt 0 ]; do
  case "$1" in
    --from-version)
      if [ -z "$2" ]; then
        echo "error: '--from-version' requires a version number" >&2
        exit 1
      fi
      shift
      from=$(echo "$1" | sed 's/^v//')
      break
      ;;
    *)
      echo "error: unknown argument '$1'" >&2
      exit 1
      ;;
  esac
done

# Current/latest tag.
current=$(git describe --tags --match='v*' --abbrev=0)
version=$(echo $current | sed 's/^v//')

if [ -z "$from" ]; then
  previous="$(git describe --abbrev=0 HEAD^)"
else
  previous="v$from"
fi

if ! git rev-parse --verify "$previous^{tag}" >/dev/null 2>&1; then
  echo "error: '$from' is not a valid version, tag '$previous' not found" >&2
  exit 1
fi

echo "# 👾 Radicle $version"
echo
echo "Radicle $version ($(git rev-parse --short HEAD)) is released."
echo
echo "## Installation"
echo
echo '```'
echo "curl -sSf https://radicle.xyz/install | sh -s -- --no-modify-path --version=$version"
echo '```'
echo
echo "## Notes"
echo
echo "* This update is recommended for everyone. No manual intervention is required."
echo
echo "## Changelog"

ncommits=$(git rev-list --count $previous..$current)
ncontribs=$(git log $previous..$current --format='%ae' | sort -u | wc -l)

echo
echo "This release contains $ncommits commit(s) by $ncontribs contributor(s)."
echo

git log --pretty=format:'* `%h` **%s** *<%ae>*' $previous..$current

echo
echo "## Checksums"
echo

echo '```'
build/checksums
echo '```'
