#!/bin/bash
# Syncs pools against themselves using database contents as filter to cleanup
# them up
# License: GPLv3

# Principles
# * Get repos dbs contents
# * Make them a include list
# * Rsync pools against themselves removing excluded files
# * Instant cleanup!

set -euE -o pipefail
source "$(dirname "$(readlink -e "$0")")/../config"
source "$(dirname "$(readlink -e "$0")")/../db-cleanup.conf"
source "$(librelib messages)"
setup_traps

EXTRAFLAGS=()
if [[ $CLEANUP_DRYRUN = true ]]; then
	EXTRAFLAGS+=(--dry-run)
fi

filter=$(mktemp -t "${0##*/}.XXXXXXXXXX")
trap "rm -f -- ${filter@Q}" EXIT

for dbfile in "${FTP_BASE}"/*/os/*/*.db; do
	msg 'Processing %s' "$dbfile"
	bsdtar tf "${dbfile}"
done | cut -d'/' -f1 | sort -u | sed "s|$|*|" > "$filter"

msg "Removing old files:"

for POOL in "${PKGPOOLS[@]}" "${SRCPOOLS[@]}" "${TORRENTPOOLS[@]}"; do
	msg2 '%s' "${POOL}"

	rsync "${EXTRAFLAGS[@]}" -va --delete-excluded \
		--include-from="$filter" \
		--exclude="*" \
		"${FTP_BASE}/${POOL}/" \
		"${FTP_BASE}/${POOL}/"
done

msg "Removing dead symlinks:"
actions=(-print)
if [[ $CLEANUP_DRYRUN != true ]]; then
	actions+=(-delete)
fi
find -L "${FTP_BASE}/" -type l "${actions[@]}"
