#!/bin/bash

FAKECHROOTDIR="$1"
PACKAGELIST=${@:2}

LOG="${LOG:-/dev/null}"

SAVEDIFFS="${SAVEDIFFS:-"yes"}"

hashsum() {
	md5sum "$1" | cut -d ' ' -f 1
}

remove() {
	/bin/rm $@
}

for package in $PACKAGELIST; do
	if rpm -q $package >$LOG 2>&1 ; then
		rpm -ql $package 2>/dev/null | while IFS= read -r f; do
			if [ -d "${f}" ]; then
				continue
			fi
			hash_src=$(hashsum "${f}")
			hash_dst=$(hashsum "${FAKECHROOTDIR}${f}")
			if [ "$hash_src" != "$hash_dst" ]; then
				echo "[WARN] ${FAKECHROOTDIR}${f} != ${f}"
				diff -u "${f}" "${FAKECHROOTDIR}${f}"
				if [ "$SAVEDIFFS" == "no" ]; then
					remove "${FAKECHROOTDIR}${f}" >$LOG 2>&1
				fi
			else
				remove "${FAKECHROOTDIR}${f}" >$LOG 2>&1
			fi
		done
		echo "[OK] Removed: $package"
	else
		echo "[ERROR] Not found: $package"
		exit
	fi
done

# also remove empty directories
find "$FAKECHROOTDIR" -depth -type d -empty -delete
