#!/bin/bash
#
# news.bash - enumerate the titles of issues and pull-requests closed between FROM..TO
#
# Copyright (C) 2023 Masatake YAMATO
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
FROM=v6.1.0
TO=.
PROJ=universal-ctags
REPO=ctags

args=("$@")

pr_title()
{
    local N=$1
    curl --no-progress-meter https://github.com/${PROJ}/${REPO}/pull/"$N" | grep '^  <title>' | \
	sed -e 's!^[[:space:]]*<title>\(.\+Pull Request #[0-9]*\).*</title>$!* \1!' | \
	sed -e "s/&#39;/'/g" -e 's/&amp;/\&/g' -e 's/&quot;/"/g' -e 's/&gt;/>/g' -e 's/&lt;/</g'
}

issue_title()
{
    local N=$1
    curl --no-progress-meter https://github.com/${PROJ}/${REPO}/issues/"$N" | grep '^  <title>' | \
	sed -e 's!^[[:space:]]*<title>\(.\+Issue #[0-9]*\).*</title>$!* \1!' | \
	sed -e "s/&#39;/'/g" -e 's/&amp;/\&/g' -e 's/&quot;/"/g' -e 's/&gt;/>/g' -e 's/&lt;/</g'
}

usage()
{
    printf "	%s help|--help|-h\n" "$0"
    printf "	%s pr [#]\n" "$0"
    printf "	%s issue [#]\n" "$0"
    printf "	%s man\n" "$0"
}

if [[ $# == 0 ]]; then
    usage 1>&2
    exit 1
fi

case $1 in
    (help|--help|-h)
	usage 1>&2
	exit 0
	;;
    (pr)
	shift
	if [[ $1 =~ [0-9]+ ]]; then
	    pr_title "$1"
	    exit 0
	else
	    echo
	    echo ".. generated by $0 ${args[@]}" "[$FROM..$TO]"
	    echo
	    git log --oneline ${FROM}..${TO} \
		| grep '[0-9a-f]\+ Merge pull request #[0-9]\+.*' \
		| sed -ne 's/.*#\([0-9]\+\) from.*/\1/p' | while read N; do
		pr_title "$N"
	    done
	    exit 0
	fi
	;;
    (issue)
	shift
	if [[ $1 =~ [0-9]+ ]]; then
	    issue_title "$1"
	    exit 0
	else
	    echo
	    echo ".. generated by $0 ${args[@]}" "[$FROM..$TO]"
	    echo
	    git log ${FROM}..${TO} \
		| sed -ne 's/^[[:space:]]*\(Partially\)\?[[:space:]]*\(closed\?\|fix\(ed\)\?\) *#\([0-9]\+\).*/\4 (\1)/Ip' \
		| sed -e  's/()//' | while read N; do
		issue_title $N
	    done | uniq
	fi
	;;
    (man)
	git diff ${FROM}..${TO} man/*.in
	;;
esac
