#!/bin/sh

### This is the wrapper script for the Soapbox library
### Soapbox - A way to deny processes to write files outside some directories
###
### Copyright (C) 2003 by Dag Wieers <dag@wieers.com>
###
### More information about Soapbox at:
###
###	http://dag.wieers.com/home-made/soapbox/

VER="0.3.0"
CMD="$(basename $0)"

### Make sure that SOAPBOXPATH cannot be polluted from the outside (when set with options).
SOAPBOXPATHTEMP=""

function help {
	cat <<EOF
Usage:
    $CMD [-cfhsv] [-a action] [-d level] [-l file] [-p paths] [--] command

Soapbox - A way to deny processes to write files outside some directories

    -a action        action is one of 'warn', 'err' or 'halt'
    -c               add current working directory to path
    -d debuglevel    a number between 0 and 31 (1-4 bitwise)
    -f               overwrite logfile (instead of appending)
    -h               display this help and exit
    -l logfile       log to a logfile
    -p paths         list of directories where writing is allowed
    -s               safe path (eg. /dev/tty, /dev/null, /tmp, /var/tmp)
    -v               output version information and exit

Example:
    $CMD -l log -p /tmp:/var/tmp/test -- make DESTDIR=/var/tmp/test install

Report bugs to: Dag Wieers <dag@wieers.com>.
EOF
	exit 0
}

### Check options
OPTIND=1
while getopts "cfhsva:d:l:p:-:" c; do
	case "$c" in
		(f)	REMOVELOG="true";;
		(c)	SOAPBOXPATHTEMP="$SOAPBOXPATHTEMP:$PWD";;
		(s)	SOAPBOXPATHTEMP="$SOAPBOXPATHTEMP:$(tty):/dev/tty:/dev/null:/tmp:/var/tmp";;
		(p)	SOAPBOXPATHTEMP="$SOAPBOXPATHTEMP:$OPTARG";;
		(a)	SOAPBOXACTION="$OPTARG";;
		(d)	SOAPBOXDEBUG="$OPTARG";;
		(l)	SOAPBOXLOG="$OPTARG";;
		(h)	help;;
		(v)	echo "soapbox $VER"
			exit 0;;
		(-)	break 2;;
		(*)	echo -e "Try \`soapbox -h' for more information." >&2
			exit 1
			;;
	esac
done
shift $((OPTIND-1))

### If any paths were added, make it so
if [ "$SOAPBOXPATHTEMP" ]; then
	SOAPBOXPATH="$SOAPBOXPATHTEMP"
fi

### Empty command ?
if [ -z "$*" ]; then
	echo "$CMD: no command specified." >&2
	echo "Try \`$CMD -h' for more information." >&2
	exit 2
fi

### Remove logfile
if [ "$SOAPBOXLOG" -a -w "$SOAPBOXLOG" -a "$REMOVELOG" == "true" ]; then
	rm -f "$SOAPBOXLOG"
fi

### Show some debugging info (-d 8 will do this too)
#if [ $SOAPBOXDEBUG -gt 0 ]; then
#	[ "$SOAPBOXACTION" ] && echo "SOAPBOXACTION=$SOAPBOXACTION" >&2
#	[ "$SOAPBOXPATH" ] && echo "SOAPBOXPATH=$SOAPBOXPATH" >&2
#	[ "$SOAPBOXLOG" ] && echo "SOAPBOXLOG=$SOAPBOXLOG" >&2
#fi

### Export variables
export SOAPBOXACTION SOAPBOXDEBUG SOAPBOXLOG SOAPBOXPATH

### Preload Soapbox
export LD_PRELOAD="/lib/libsoapbox.so:$LD_PRELOAD"

exec $@
