#!/bin/sh

# based on work of Dmitry E. Oboukhov <unera <at> debian.org>
# http://uvw.ru/find_the_bug2.sh
# adapted for repocop by viy at altlinux.org

cwd=`pwd`
report_name="$REPOCOP_TEST_TMPDIR/report"
cat > $report_name <<'EOH'
The test discovered scripts with errors which may be used
by a user for damaging important system files.

For example if a script uses in its work a temp file which is created
in /tmp directory, then every user can create symlinks with the same
name (pattern) in this directory in order to destroy or rewrite some 
system or another user's files.

Scripts _must_ _use_ mktemp/tempfile or must use $TMPDIR.
mktemp/tempfile is safest. $TMPDIR is safer than /tmp/ 
because libpam-tmpdir creates a subdirectory of /tmp
that is only accessible by that user, and then sets TMPDIR and other
variables to that. Hence, it doesn't matter nearly as much if you
create a non-random filename, because nobody but you can access it.

EOH

cd $REPOCOP_PKG_ROOT
not_an_example_flag="$REPOCOP_TEST_TMPDIR/notanexample"
rm -f "$not_an_example_flag"
find . -type f -perm /111 | while read package_efile; do
        file $package_efile|grep -q script || continue
        if ! sed 's/#.*//' $package_efile|grep -q '/tmp/'; then
            continue
        fi

        file_found=''
        # checks
        sed 's/#.*//' $package_efile| \
            grep -q '>[[:space:]]*/tmp/' && file_found=1
        sed 's/#.*//' $package_efile| \
            grep -q 'tee[[:space:]][^|]*/tmp/' && file_found=1

        if test -z "$file_found"; then
            continue
        fi
        root_path_efile=`echo $package_efile|sed 's/^.//'`
        echo "Found error in $root_path_efile:" >> $report_name
        echo -e "\t\$ grep -A5 -B5 /tmp/ $root_path_efile" >> $report_name
        grep -A5 -B5 /tmp/ $package_efile|sed 's/^/\t/' >> $report_name
	case $root_path_efile in 
	     /usr/share/doc/*/examples/*) : ;;
	     *) touch "$not_an_example_flag" ;;
	esac
done
cd $cwd

if grep 'Found error' $report_name; then
    if grep '^'$REPOCOP_PKG_NAME'$' /usr/share/repocop/pkgtests/unsafe-tmp-usage-in-scripts/whitelist >/dev/null; then
        : # skip
    elif grep '^'$REPOCOP_PKG_NAME'$' /usr/share/repocop/pkgtests/unsafe-tmp-usage-in-scripts/graylist >/dev/null; then
        repocop-test-info `cat $report_name`
    elif [ -e "$not_an_example_flag" ]; then
        repocop-test-fail `cat $report_name`
    else
        repocop-test-info `cat $report_name`
    fi
else
    repocop-test-ok
fi
rm -f $report_name
