#! /bin/bash
#
# ssmexec

# GPL--start
# This file is part of ssm (Simple Software Manager)
# Copyright (C) 2005-2010 Environment/Environnement Canada
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; version 2
# of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
# GPL--end

printUsage() {
	echo "usage: ssmexec [options] <fileName> [args]

Execute directly a published binary independent of
any environment preparation as is typical when running
across a remote shell (e.g., rsh).

Where options are:
    -h|--help
    -d|--domainHome <path>|<relpath>
        The path to the new domain to be set up.
        Default:
            ${domainHome}
    --dry
        Do a dry run. Do not execute the command.
    --verbose
        Be verbose. Indicate what is going on."
}

lecho() {
    if [ ${verbose} -eq 1 ]; then
        echo $*
    fi
}

# defaults/setup
domainHome=/opt/ssm
fileName=""
dry=0
verbose=0

# main
while [ $# -gt 0 ]; do
	case $1 in
	"-d"|"--domainHome")
		shift 1
		domainHome=$1; shift 1
		;;
	"--dry")
		dry=1; shift 1
		;;
	"-h"|"--help")
		printUsage
		exit 1
		;;
	"-v"|"--verbose")
		verbose=1; shift 1
		;;
	*)
		fileName=$1; shift 1
		break
		;;
	esac
done

if [ "${fileName}" = "" ]; then
	printUsage
	exit 1
fi

ssm_lib=${domainHome}/lib/ssm.d/ssm_lib.sh
if [ -r ${ssm_lib} ]; then
	. ${ssm_lib}
	platforms=`getSystemPlatforms "${domainHome}"`
	#lecho "platforms: ${platforms}"
	#lecho "fileName:  ${fileName}"
	for platform in ${platforms}; do
		filePath="${domainHome}/${platform}/bin/${fileName}"
		lecho "Checking command ($filePath)."
		if [ -x ${filePath} ]; then
			lecho "Running command ($filePath)."
			if [ ${dry} -eq 1 ]; then
				exit 0
			fi
			exec ${filePath} "$@"
		fi
	done
	echo "Error: Cannot find file (${fileName})."
else
	echo "Error: Cannot find required file (${ssmLib})."
fi

exit 1
