#!/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

TMPFILE="$(mktemp --tmpdir=/tmp/ .$(basename ${0})-${$}-XXXXXX)"

cd ${BASEDIR}/

# remove source files older 90 days
find ${SRCDEST:-src}/ -maxdepth 1 -type f -ctime +90 -exec rm -f {} \;

# remove dead links
find -type l -follow -exec rm -f {} \;

# generate temporary list of package files
for ARCH in x86_64; do
	gzip -cd ${REPODIR}/${ARCH}/${REPONAME}.db.tar.gz | bsdtar -xOf - '*/desc' | sed -n '/%FILENAME%/{n;p;}' >> ${TMPFILE}
done

# delete packages not in db
for FILE in $(find -L ${REPODIR}/ -type f -name '*.pkg.*' | grep -E -v '.sig$'); do
	if ! grep -q $(basename "${FILE}") ${TMPFILE}; then
		rm -vf ${FILE}
	fi
done

# delete signatures without package
for SIG in $(find -L ${REPODIR}/ -type f -name "*.pkg.*.sig"); do
	[ ! -e ${SIG%.sig} ] && rm -fv ${SIG}
done

# warn about missing packages that are listed in the db
for ARCH in x86_64; do
	for FILE in $(zcat ${REPODIR}/${ARCH}/${REPONAME}.db.tar.gz | bsdtar -xOf - '*/desc' | sed -n '/%FILENAME%/{n;p;}'); do
		if [ ! -e ${REPODIR}/${ARCH}/${FILE} ]; then
			echo "File ${FILE} does not exist!" >&2
		fi
	done
done

rm ${TMPFILE}

repo-sync
