#!/usr/bin/env bash

# Copyright (C) 2019-2020, 2022-2024 Bill Auger <mr.j.spam.me@gmail.com>
# Copyright (C) 2024 Luke T. Shumaker <lukeshu@parabola.nu>
#
# License: GNU GPLv3+
#
# This file is part of Parabola.
#
# Parabola 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 3 of the License, or
# (at your option) any later version.
#
# Parabola 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 Parabola. If not, see <http://www.gnu.org/licenses/>.

. "$(librelib messages)"

# parse `librerelease` `db-update` log via STDIN,
# and emit formatted notification message
release_notification() { # ( hacker ) dbupdate_log->STDIN
	local hacker=${1:-somebody}
	#                   (pkgname             )-       :  (pkgver         )-      -(arch      )
	local filename_rx="^([0-9A-Za-z\._@\+\-]+)-([0-9]+:)?([0-9A-Za-z\._]+)-[^/-]+-([0-9a-z_]+)\.pkg\.tar\.[^\.]+$"
	local repo pkg arch pkgname pkgver

	printf "${hacker} just published: "
	grep -E "^==> Updating |^  -> [^ ]+ \([^ )]+\)" |
		while read line; do
			if [[ ${line} =~ ^==\>\ Updating\ \[([^\]]+)\]...$ ]]; then
				repo=${BASH_REMATCH[1]}
			elif [[ ${line} =~ ^\ *-\>\ ([^\ ]+)\ \(([^\ ]+)\)$ ]]; then
				pkg=${BASH_REMATCH[1]} arch=${BASH_REMATCH[2]}
				if [[ ${pkg} =~ ${filename_rx} ]]; then
					pkgname=${BASH_REMATCH[1]} pkgver=${BASH_REMATCH[3]}
					if [[ ! ${pkg} =~ '-debug-' ]]; then
						echo "(${pkgname} ${pkgver})->${repo}/${arch}"
					fi
				fi
			fi
		done | LC_COLLATE=C sort -u | xargs
}

main() {
	[[ $# -ge 3 ]] || panic
	local hacker=$1
	local dbupdate_log=$2
	local SSH_CMD=("${@:3}")

	local pbotsay_msg pbotsay_cmd

	if grep -Eq "^==> Updating \[" "$dbupdate_log"; then
		pbotsay_msg=$(release_notification "$hacker" <"$dbupdate_log")

		# notify pbot of the excellent work that we have done today
		msg2 "Notifying pbot:"
		print "     $pbotsay_msg"
		"${SSH_CMD[@]}" \
			"if type pbot-say &>/dev/null; then pbot-say ${pbotsay_msg@Q} ; fi" \
			&>/dev/null || :
	else
		msg2 "Nothing was published"
	fi
}

main "$@"
