#!/bin/bash -e

DESCRIPTION="Interactive cleanup of some cruft maybe left over from versions <= 1.0.17."

case "${1}" in
	"--help")
		cat <<EOF
Usage: mini-buildd-reject-cleanup (as user mini-buildd)

${DESCRIPTION}

Up to version 1.0.17 of mini-buildd, rejected packages where
put to the "pkglog" in "~/var/log/<repoid>/"

In case of a reject due to a malformed distribution string
like 'jessie-uff-unstable', files would have be written for
the (phantom) repository id 'uff', and also not ever being
cleaned up.

This script tries to find these stray directories and offers to purge them.
EOF
	exit 0
esac

[ "$(id -u -n)" = "mini-buildd" ] || { printf "E: Run this as user mini-buildd.\nTry 'mini-buildd-reject-cleanup --help'.\n" >&2; exit 1; }

for LOG_PATH in $(find "${HOME}/var/log/" -maxdepth 1 -mindepth 1 -type d); do
	REPO_PATH="${HOME}/repositories/$(basename "${LOG_PATH}")"
	if [ ! -d "${REPO_PATH}" ]; then
		printf "%s: Maybe stray (no corresponding repository path '%s' found).\n" "${LOG_PATH}" "${REPO_PATH}"
		ANSWER=n
		read -p "Purge now? [n]" ANSWER
		if [ "${ANSWER}" = "y" ]; then
			rm -rfv "${LOG_PATH}"
		fi
	fi
done
