#! /bin/sh --
#
#	$NetBSD: checkflist,v 1.29 2006/01/03 18:31:09 apb Exp $
#
# Verify output of makeflist against contents of ${DESTDIR}.

if [ -z "${DESTDIR}" ]; then
	echo "DESTDIR must be set"
	exit 1
fi

prog="${0##*/}"
rundir="$(dirname "$0")" # ${0%/*} isn't good enough when there's no "/"
. "${rundir}/sets.subr"

SDIR="$(${MKTEMP} -d "/tmp/${prog}.XXXXXX")"

es=0
cleanup()
{
	/bin/rm -rf "${SDIR}"
	if [ ${es} -gt 255 ] ; then
		es=255
	fi
	exit ${es}
}
trap cleanup 0 2 3 13		# EXIT INT QUIT PIPE


origin=.
xargs=""
dargs=""
metalog=
allowextra=false
allowmissing=false

# handle args
while getopts xbM:em ch; do
	case ${ch} in
	x)
		xargs="-x"
		origin="./etc/X11 ./etc/fonts ./usr/X11R6"
		;;
	b)
		xargs="-b"
		;;
	M)
		metalog="${OPTARG}"
		;;
	e)
		allowextra=true
		;;
	m)
		allowmissing=true
		;;
	*)
		cat 1>&2 <<USAGE
Usage: ${prog} [-x|-b] [-M metalog] [-e] [-m]
	-x		check only x11 lists
	-b		check netbsd + x11 lists
	-M metalog	metalog file
	-e		extra files are not considered an error
	-m		missing files are not considered an error
USAGE
		exit 1
		;;
	esac
done
shift $((${OPTIND} - 1))

if [ -n "${metalog}" ]; then
	case "${metalog}" in
	"${DESTDIR}"/*)
		# Metalog would be noticed, so make sure it gets
		# ignored.
		metalog="./${metalog#"${DESTDIR}"/}"
		;;
	*)
		metalog=""
	esac
fi


${HOST_SH} ./makeflist ${xargs} ${dargs} > "${SDIR}/flist"

(
	cd "${DESTDIR}"
	${FIND} ${origin} \( -type d -o -type f -o -type l \) -print
) | (
	while read line; do
		case "${line}" in
		"${metalog}")
			;;
		*)
			echo "${line}"
			;;
		esac
	done
) | ${SORT} > "${SDIR}/files"

${COMM} -23 "${SDIR}/flist}" "${SDIR}/files}" > "${SDIR}/missing}"
${COMM} -13 "${SDIR}/flist}" "${SDIR}/files}" > "${SDIR}/extra}"

if [ -s "${SDIR}/extra" ]; then
	count="$(${AWK} 'END {print NR}' "${SDIR}/extra")"
	echo ""
	echo "============  ${count} extra files  ==============="
	echo "Files in DESTDIR but missing from flist."
	echo "File is obsolete or flist is out of date ?"
	if ${allowextra}; then
		echo "This is non-fatal."
	else
		es=1
	fi
	echo "------------------------------------------"
	cat "${SDIR}/extra"
	echo "=========  end of ${count} extra files  ==========="
	echo ""
fi

if [ -s "${SDIR}/missing" ]; then
	count="$(${AWK} 'END {print NR}' "${SDIR}/missing")"
	echo ""
	echo "===========  ${count} missing files  =============="
	echo "Files in flist but missing from DESTDIR."
	echo "File wasn't installed ?"
	if ${allowmissing}; then
		echo "This is non-fatal."
	else
		es=1
	fi
	echo "------------------------------------------"
	cat "${SDIR}/missing"
	echo "========  end of ${count} missing files  =========="
	echo ""
fi

exit 0		# cleanup will exit with ${es}
