#!/usr/bin/env bash
# archlog -- show changelog for an Arch Linux package

. lib.bash || exit

usage() {
	echo "Usage: $progname [-av] <package>"
	echo
	echo_opt "-a"		"show all branches (e.g. gnome-unstable)"
	echo_opt "-v"		"show all files (including PGP keys, etc.)"
}

basedir="${XDG_CACHE_HOME:-$HOME/.cache}/asp"
opt_allrefs=0
opt_verbose=0

while getopts :av OPT; do
	case $OPT in
	a) opt_allrefs=1;;
	v) opt_verbose=1;;
	*) lib:die_getopts;;
	esac
done; shift $((OPTIND-1))

if (( ! $# )); then
	vdie "package name not specified"
fi

if [[ ! -d $basedir ]]; then
	mkdir -p "$basedir"
fi

ref=""
if (( opt_allrefs )); then
	ref="--all"
fi

for pkg; do
	# Fix up tab-completion
	pkg=${pkg#*/}

	# Look up pkgbase if a binary package is specified
	pkgbase=$(expac -S -1 %e "$pkg" || echo "$pkg")
	if [[ "$pkg" != "$pkgbase" ]]; then
		vmsg "using '$pkgbase' as source package name for '$pkg'"
		pkg=$pkgbase
	fi

	# Convert to a repository name per GitLab rules
	pkgrepo=$(sed -E '
			s/([a-zA-Z0-9]+)\+([a-zA-Z]+)/\1-\2/g;
			s/\+/plus/g;
			s/[^a-zA-Z0-9_\-\.]/-/g;
			s/[_\-]{2,}/-/g;
			s/^tree$/unix-tree/g;
		' <<< "$pkg")
	if [[ "$pkgrepo" != "$pkg" ]]; then
		vmsg "using '$pkgrepo' as repository name for '$pkgbase'"
		pkg=$pkgrepo
	fi

	dir="$basedir/$pkg"
	url="https://gitlab.archlinux.org/archlinux/packaging/packages/$pkg.git"

	# Update the repository
	if [[ ! -d $dir ]]; then
		vmsg "cloning '$pkg'"
		GIT_TERMINAL_PROMPT=0 git clone --quiet "$url" "$dir"
	else
		vmsg "updating '$pkg'"
		GIT_TERMINAL_PROMPT=0 git -C "$dir" pull --quiet --ff-only
	fi || vdie "repository '$pkg' could not be updated"

	# Always hide really verbose PGP-key diffs
	if [[ ! -e $basedir/.gitattributes ]]; then
		cat > "$basedir/.gitattributes" <<-!
		# Symlinked into each repository's .git/info/attributes
		/keys/pgp/*.asc -diff
		!
	fi
	if [[ ! -e $dir/.git/info/attributes ]]; then
		ln -rnsf "$basedir/.gitattributes" "$dir/.git/info/attributes"
	fi

	# Optionally hide redundant .SRCINFO diffs
	paths=()
	if (( !opt_verbose )); then
		paths+=(":!/.SRCINFO")
		paths+=(":!/keys/pgp")
	fi

	settitle "asplog [$pkg]"

	tig -C "$dir" "$ref" -- "${paths[@]}"
done
