#!/bin/ksh
# $Id: sudop.ksh,v 1.8 2008/12/05 20:17:42 ksb Exp $
# $Source: /usr/msrc/usr/local/bin/sudop/RCS/sudop.ksh,v $
#
# People really like sudo syntax. Go figure.   --jad
# This won't work without the op rule from the README file, which we put
# in the "access.cf" file in the source to op_lib.  You might have to put
# that rule in some other place.

: ${op:=/usr/local/libexec/sudop/sudo}

PROGNAME=`basename $0`

function usage {
	echo "usage: $PROGNAME -V | -h | -L | -l | -v | -k | -K | [-H] [-P] [-S] [-b] [-p prompt]" 1>&2
	echo "            [-u username/#uid] [-r role] [-t type] -s | <command>" 1>&2
}

# Process options
# Sudo can't handle multiple single-letter switches behind a single dash, so neither are we.
OPT_G=""
OPT_U=""
while [ -n "$1" ] ; do
	case _"$1" in
	_-V)
		echo "$PROGNAME: "'$Id: sudop.ksh,v 1.8 2008/12/05 20:17:42 ksb Exp $'
		${op} -V
		exit 0
		;;
	_-l)
		IFS=:
		${op} sudomap -l |
			while read  user sudorule ; do
				echo "	(${user})	${sudorule}"
			done
		exit 0
		;;
	_-h)
		usage
		exit 0
		;;
	_-g)	OPT_G=${2?'-g: missing groupname'}
		shift
		;;
	_-u)	OPT_U=${2?'-u: missing username'}
		shift
		;;
	_-b)
		BACKGROUND=1
		;;
	_-s)
		echo "$PROGNAME: shell access forbidden; specific command must be given"
		exit 1
		;;
	# Eat most options.
	_-L)	;;
	_-v)	;;
	_-K)	;;
	_-H)	;;
	_-P)	;;
	_-S)	;;
	_-p)	shift ;;
	_-c)	shift ;;
	_-a)	shift ;;
	_-r)	shift ;;
	_-t)	shift ;;
	_--)
		shift
		break
		;;
	_-*)
		usage
		exit 1
		;;
	_*)
		break
		;;
	esac
	shift
done
# No more switches

# First positional parameter is sudo-like full path to a command. Required.
COMMAND="$1"
shift
# Collapse all multiple slashes to single slashes
COMMAND="`echo \"$COMMAND\" | sed -e 's,//*,/,g'`"
if [ -z "$COMMAND" ] ; then
	usage
	exit 2
fi

# Try to find the matching op rule for the path
MAPPED=$(${op} sudomap ${OPT_U:+ -u $OPT_U}${OPT_G:+ -g $OPT_G} $COMMAND)
if [ -z "$MAPPED" ] ; then
	echo "$PROGNAME: Permission denied" 1>&2
	exit 1
fi

# Pass all arguments to op rule verbatim. Background the job if requested.
if [ -n "$BACKGROUND" ] ; then
	( $op $MAPPED "$@" & )
	exit 0
fi
exec $op $MAPPED "$@"
