#!/bin/bash -e

. $(dirname $0)/mbd-common.sh

mbd_opt_init "Mini-buildd: Remove package(s) from the repository.

 * Will not actually do anything unless you specify -R.
 * On -R, package(s) will be removed from repo by moving to a directory in ~/REMOVED.
 * Depends on changes files; packages (wrongly) installed without cannot be removed.

Examples:
 mbd-remove-pkg -p \"*_*_*\"            : Remove all packages.
 mbd-remove-pkg -p \"etch*/*_*_*\"      : Remove all packages from all etch distributions.
 mbd-remove-pkg -p \"PACKAGE_*_*\"      : Remove all versions of PACKAGE.
 mbd-remove-pkg -p \"PACKAGE_1.2.3-1_*\": Remove exact version 1.2.3-1 of PACKAGE."
mbd_opt_add "p:" "Pattern (see find(1)) for package changes file(s) to work on."
mbd_opt_add "s" "Stop mini-buildd while running."
mbd_opt_add "v" "Be verbose."
mbd_opt_add "R" "Actually do removal -- BE SURE YOU GOT THE PACKAGES RIGHT BEFORE DOING THAT."
mbd_opt_parse "$@"

PACKAGE=$(mbd_opt_get p)
REMOVEDIR="${MBD_HOME}/REMOVED/$(date --utc +%Y%m%d:%H%M%S:%N)"
ADDARGS=""
if mbd_opt_given v; then
	ADDARGS="-v"
fi

mbd_remove_file()
{
	local f="${1}"
	local cmd="mv ${ADDARGS} ${1} ${REMOVEDIR}/"

	if mbd_opt_given R; then
		mkdir ${ADDARGS} -p "${REMOVEDIR}"
		[ ! -e "${f}" ] || ${cmd}
	else
		if mbd_opt_given v; then
			echo "Would run: ${cmd}"
		fi
	fi
}

if mbd_opt_given s; then
	/etc/init.d/mini-buildd-rep stop
fi

# Iterate over all changes files
for c in $(find ${MBD_HOME}/rep/ -type f -wholename "${PACKAGE}.changes"); do
	dir=$(dirname ${c})
	mbdParseCF "${c}"
	log="${MBD_HOME}/log/$(echo "${mbdParseCF_package}" | cut -d_ -f1)/${mbdParseCF_version}"

	echo "Found: ${c}"

	for f in ${mbdParseCF_files}; do
		mbd_remove_file "${dir}/${f}"
	done
	mbd_remove_file "${dir}.db"
	mbd_remove_file "${log}"
done

if mbd_opt_given s; then
	/etc/init.d/mini-buildd-rep start
fi

if mbd_opt_given R; then
	echo "Files moved to ${REMOVEDIR}."
fi
