#!/usr/bin/bash
shopt -s nullglob

parse_pkg_filename() {
	declare filename=$1
	declare -a filename_array

	IFS='-' read -r -a filename_array <<< "$filename"

	for (( i=${#filename_array[@]}; i>=0; i-- )); do
		printf '%s ' "${filename_array[$i]}"
	done
}

is_latest() {
	declare filename=$1 p

	for p in "${latest[@]}"; do
		if [[ "$filename" == "$p" ]]; then
			return 0
		fi
	done

	return 1
}

_pacsort() {
	declare i

	for i in *.pkg.tar.xz; do
		printf '%s\n' "$i"
	done | pacsort -f
}

while (( $# )); do
	case "$1" in
		-r) flag_rm=1;;
		-d) flag_debug=1;;
	esac
	shift
done

if ! (( flag_rm )); then
	if ! [[ -d old ]]; then
		mkdir -p old || {
			return 1
		}
	fi
fi

read -d '' -r -a package_files < <( _pacsort )

for f in "${package_files[@]}"; do
	unset revision version end package_name

	read -r end revision version _ < <(parse_pkg_filename "$f")
	package_name=${f%%-$version-$revision*}

	declare -g -A latest["$package_name"]="$package_name-$version-$revision-$end"
done

for f in ${package_files[@]}; do
	if is_latest "$f"; then
		(( flag_debug )) && printf '%s is the latest version available\n' "$f"
	else
		printf 'Removing: %s\n' "$f"

		if (( flag_rm )); then
			rm -f "$f" "${f}.sig"
		else
			mv "$f" old/

			if [[ -f "${f}.sig" ]]; then
				mv "${f}.sig" old/
			fi
		fi
	fi
done

if [[ -d old ]]; then
	cd old
	exec bash "$0" -r
fi