#!/bin/bash

echo "... testing for modified permissions"
TOPDIR=/usr/src/packages
test -d $BUILD_ROOT/.build.packages && TOPDIR=/.build.packages
test -f $BUILD_ROOT/etc/sysconfig/security || exit 0

HAD_ERRORS=0

grep -q "secure local" $BUILD_ROOT/etc/sysconfig/security || {
    echo "ERROR: expected permission level to be set to secure ?!"
    HAD_ERRORS=1
}

RPM="chroot $BUILD_ROOT env LC_ALL=C rpm --nodigest --nosignature -Vp --nofiledigest --nodeps"

for i in $(find $BUILD_ROOT$TOPDIR/RPMS -type f -name "*.rpm" | LC_ALL=C sort) ; do
    case "$pkg" in
        *-debuginfo-*|*-debugsource-*) continue ;;
    esac
    $RPM ${i#$BUILD_ROOT} > $BUILD_ROOT/.build_rpmVp_orig
    sed -i.bak -e "s@^PERMISSION_SECURITY\(.*\)@PERMISSION_SECURITY = \"easy local\"@" \
           $BUILD_ROOT/etc/sysconfig/security
    chroot $BUILD_ROOT /usr/bin/chkstat --set --system >/dev/null 2>&1
    $RPM ${i#$BUILD_ROOT} > $BUILD_ROOT/.build_rpmVp_easy
    sed -i -e "s@^PERMISSION_SECURITY\(.*\)@PERMISSION_SECURITY = \"paranoid local\"@" \
           $BUILD_ROOT/etc/sysconfig/security
    chroot $BUILD_ROOT /usr/bin/chkstat --set --system >/dev/null 2>&1
    $RPM ${i#$BUILD_ROOT} > $BUILD_ROOT/.build_rpmVp_paranoid
    mv $BUILD_ROOT/etc/sysconfig/security.bak $BUILD_ROOT/etc/sysconfig/security
    chroot $BUILD_ROOT /usr/bin/chkstat --set --system >/dev/null 2>&1
    if ! cmp -s $BUILD_ROOT/.build_rpmVp_orig $BUILD_ROOT/.build_rpmVp_easy; then
	echo "--------------------------------------------------------------------"
	echo "ERROR: chkstat --level secure modified package $(rpm --nodigest --nosignature -qp --qf '%{NAME}' \"$i\")"
	echo "Please add '%verify(not mode,...) for those to avoid listings in rpm -V."
	echo "diff for both runs of rpm -V:"
	diff -u0 "$BUILD_ROOT/.build_rpmVp_orig" "$BUILD_ROOT/.build_rpmVp_easy"
	echo "--------------------------------------------------------------------"
	HAD_ERRORS=1
    fi
    if ! cmp -s $BUILD_ROOT/.build_rpmVp_orig $BUILD_ROOT/.build_rpmVp_paranoid; then
	echo "--------------------------------------------------------------------"
        echo "ERROR: chkstat --level paranoid modified package $(rpm --nodigest --nosignature -qp --qf '%{NAME}' \"$i\")"
        echo "Please add '%verify(not mode,...) for those to avoid listings in rpm -V."
	echo "diff for both runs of rpm -V:"
	diff -u0 "$BUILD_ROOT/.build_rpmVp_orig" "$BUILD_ROOT/.build_rpmVp_paranoid"
	echo "--------------------------------------------------------------------"
	HAD_ERRORS=1
    fi
done

rm -f $BUILD_ROOT/.build_rpmVp_{orig,secure,paranoid}

if test "$HAD_ERRORS" = 1 ; then
	touch $BUILD_ROOT/not-ready
	exit 1
fi
exit 0
