#!/bin/sh

source /etc/makepkg.conf
if [ -e "${XDG_CONFIG_HOME}/pacman/makepkg.conf" ]; then
	source "${XDG_CONFIG_HOME}/pacman/makepkg.conf"
elif [ -e ~/.makepkg.conf ]; then
	source ~/.makepkg.conf
fi
source /etc/conf.d/eworm-repo
source /usr/lib/eworm/noroot
source /usr/lib/eworm/nice

# There may be some implications where gpg-agent starts X11 pinentry. So
# unset DISPLAY and have ncurses pinentry.
unset DISPLAY

function help() {
	echo "usage: ${0} [OPTIONS]"
	echo
	echo "where OPTIONS are:"
	echo " -a ARCH     download for architecture ARCH"
	echo " -h          show this help"
	echo " -p PACKAGE  download PACKAGE from [testing]"
}

ARCH=""
NEWURL=""
PACKAGE=""

while getopts "a:hp:" opt; do
	case ${opt} in
		a)
			case "${OPTARG}" in
				x86_64)
					ARCH="x86_64"
					;;
				*)
					echo "Architecture '${OPTARG}' is unknown." >&2
					help
					exit 1
					;;
			esac
			;;
		h)
			help
			exit 0
			;;
		p)
			PACKAGE="${OPTARG}"
			;;
	esac
done

if [ -z "${ARCH}" ]; then
	ARCH="$(uname -m)"
fi
if [ -z "${PACKAGE}" ]; then
	echo "Error: No package given!" >&2
	help
	exit 1
fi

for ANYARCH in ${ARCH} any; do
	[ "${ARCH}" = "x86_64" ] && MULTILIB="multilib-testing"
	for REPO in core-testing extra-testing ${MULTILIB}; do
		NEWURL="$(curl --head https://archlinux.org/packages/${REPO}/${ANYARCH}/${PACKAGE}/download/ 2>&1 | grep -i '^Location:' | tr -d '\r' | cut -d' ' -f2)"
		if [ -n "${NEWURL}" ]; then
			break 2
		fi
	done
done

if [ -z "${NEWURL}" ]; then
	echo "Did not get a redirect url, exiting." >&2
	exit 1
fi

if ! grep -E -q "^${PACKAGE}$" ${BASEDIR}/testing.${ARCH}; then
	echo "${PACKAGE}" >> ${BASEDIR}/testing.${ARCH}
fi

if wget -P ${REPODIR}/${ARCH}/ -c "${NEWURL}"; then
	wget -P ${REPODIR}/${ARCH}/ -c "${NEWURL}.sig"

	FILE="$(basename "${NEWURL}")"

	if ! gpg --quiet --no-permission-warning --homedir /etc/pacman.d/gnupg/ --verify ${REPODIR}/${ARCH}/${FILE}.sig; then
		echo "Providedd signature is invalid!" >&2
		exit 1
	fi

	if ! repo-add --verify --key "${GPGKEY}" --sign ${REPODIR}/${ARCH}/${REPONAME}.db.tar.gz ${REPODIR}/${ARCH}/${FILE}; then
		echo "Could not add to database file." >&2
		exit 1
	fi

	date +"%s" > ${REPODIR}/lastupdate

	# try to link to local cache dir, but do not complain on error
	if ! ln ${REPODIR}/${ARCH}/${FILE}{,.sig} /var/cache/pacman/pkg/ >/dev/null 2>/dev/null; then
		ln -srf ${REPODIR}/${ARCH}/${FILE}{,.sig} /var/cache/pacman/pkg/ >/dev/null 2>/dev/null
	fi

	repo-sync
else
	exit $?
fi
