#!/bin/bash -e

DESCRIPTION="List probable cruft files (from older versions or bugs)"

case "${1}" in
	""|"--interactive-remove"|"--automatic-remove")
		true
		;;
	*)
		cat <<EOF
Usage: $(basename "${0}") [--interactive-remove|--automatic-remove] (as user mini-buildd)

${DESCRIPTION}

--interactive-remove: Removal prompt for each found cruft
--automatic-remove  : Remove all found cruft w/o interaction
EOF
		exit 0
esac

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

# Gather (desc & solution) in two symmetric arrays
declare -a DESCRIPTION=()
declare -a SOLUTION=()

_add_path()
{
	local path="${1}"
	if [[ "${1}" != /* ]]; then
		path="${HOME}/${1}"
	fi
	if [ -e "${path}" ]; then
		DESCRIPTION+=("$(printf "%-50s (%5s): %s\n" "${path}" "$(du --summarize --human-readable "${path}" | cut -f1)" "${2:-Possible cruft file}")")
		SOLUTION+=("rm --verbose --recursive ${path}")
	fi
}

_add_outdated_paths_in()
{
	local p
	for p in $(find "${HOME}/${1}/" -maxdepth 1 -mindepth 1 -mtime +30); do
		_add_path "${p}" "${2}"
	done
}

_add_path ".mini-buildd.pid"   "No longer used, even in sysv mode"
_add_path "var/chroots-libdir" "Old libdir location"
_add_path "var/spool"          "Old spool directory"

for P in $(find "${HOME}/var/log/" -maxdepth 1 -mindepth 1 -not -regex '.*\(access.log.*\|daemon.log.*\|inspect.json.*\)'); do
	_add_path "${P}" "Old per-repo log dir"
done

for P in $(find "${HOME}/var/log/" -maxdepth 1 -mindepth 1 -name "daemon.log*"); do
	_add_path "${P}" "Old daemon.log file no longer used since 2.1.5"
done

_add_outdated_paths_in "var/tmp"          "Tempfile not changed for one month or longer, most likely stale"
_add_outdated_paths_in "var/shared/debug" "Debug copies (from ``mini-buildd-debug-build``) not changed for one month or longer"
_add_outdated_paths_in "incoming"     "Incoming file not changed for one month or longer, most likely stale"

for S in $(schroot --all-sessions --list | grep mini-buildd); do
	DESCRIPTION+=("${S}: Stale schroot session")
	SOLUTION+=("schroot --verbose --chroot=${S} --end-session")
done

if command -v lvdisplay >/dev/null 2>&1; then
	for S in $(lvdisplay 2>/dev/null | grep 'LV Name.*/dev/mini-buildd-loop-.\+/mini-buildd-.\+-.\+-.\+-.\+-.\+-.\+' | rev | cut -d' ' -f1 | rev); do
		DESCRIPTION+=("${S}: Stale LVM snapshot")
		SOLUTION+=("lvremove --verbose --force ${S}")
	done
fi

for ((N=0; N < ${#DESCRIPTION[@]}; N++ )); do
	REMOVE="N"

	printf "%s\n" "${DESCRIPTION[${N}]}"
	if [ "${1}" == "--interactive-remove" ]; then
		read -e -p "Solve using '${SOLUTION[${N}]}' ('Y' to actually do it)? " REMOVE
	elif [ "${1}" == "--automatic-remove" ]; then
		REMOVE="Y"
	fi

	if [ "${REMOVE}" = "Y" ]; then
		${SOLUTION[${N}]} || true
	fi
done
