#!/bin/sh
#
# $Id: //NW/dev/nw_8_2_1/nsr/scripts/nsr_envexec.sh#1 $ Copyright (c) 2011 EMC Corporation
#

#
# Copyright (c) 2011 EMC Corporation.
#
# All rights reserved.  This is an UNPUBLISHED work, and
# comprises proprietary and confidential information of EMC.
# Unauthorized use, disclosure, and distribution are strictly
# prohibited.  Use, duplication, or disclosure of the software
# and documentation by the U.S. Government is subject to
# restrictions set forth in a license agreement between the
# Government and EMC or other written agreement specifying
# the Government's rights to use the software and any applicable
# FAR provisions, such as FAR 52.227-19.
#

#
# Source Bourne shell scripts to set the environment, and then
# execute the remaining arguments as a shell command.
#

usage()
{
	echo "Usage: $1 [-u user_env_file] [-s sys_env_file] command [argument...]"
}

# Local variables
USR_ENV_FILE=
SYS_ENV_FILE=

while getopts "u:s:" ARG
do
	case $ARG in
	u) USR_ENV_FILE=$OPTARG;;
	s) SYS_ENV_FILE=$OPTARG;;
	\?) usage "$0" >&2; exit 1;;
	esac
done

shift `expr $OPTIND - 1`
if [ $# -lt 1 ]
then
	usage "$0" >&2
	exit 1
fi

# Source a user environment file if exists.
if [ -f "$USR_ENV_FILE" ]
then
	# Ensure that others are not given write permission
	m=`LC_ALL=C ls -l "$USR_ENV_FILE" | cut -c 9`
	if [ "$m" = "w" ]
	then
		fmt >&2 <<EOF
WARNING: Ignored user environment file '$USR_ENV_FILE' for a security reason.
Examine the contents of the file, and ensure that the file has no write
permission to 'others'.
EOF
	else
		. "$USR_ENV_FILE" || echo >&2 \
			"WARNING: Unable to source user environment file '$USR_ENV_FILE'"
	fi
fi

# Source a NetWorker system environment file if given.
if [ ! -z "$SYS_ENV_FILE" ]
then
	if [ -r "$SYS_ENV_FILE" ]
	then
		. "$SYS_ENV_FILE"
	else
		echo >&2 "WARNING: Unable to source environment file '$SYS_ENV_FILE'"
	fi
fi

# Execute the remaining arguments as a shell command.
exec "$@"
