#!/bin/bash
#
# dsh_ipass:	DSH with Password Prompt for sudo
#
# $Id: dsh_ipass 492 2013-05-10 11:16:15Z whitestar $
#
# Copyright 2012-2013 the original author or authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# 	http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

PATH="/sbin:/usr/sbin:/bin:/usr/bin"
NAME="dsh_ipass"
DESC="DSH with Password Prompt for sudo"

# Settings


ARGC="$#"
ARGS="$@"
COMMAND=$1


help() {
	echo "Usage: dsh_ipass [-P password] [argument(s) with 'sudo -S' for dsh]"
	echo 'e.g. dsh_ipass -m target.example.com -- sudo -S uptime'
}


while getopts :P:h OPT; do
	case $OPT in
		'h') 
			help
			exit 0
			;;
		'P') PASSWD=$OPTARG;;
	esac
done


# Validation
if [ $ARGC -eq 0 ]; then
	help
	exit 1
elif [ x"$COMMAND" = x'help' ]; then
	help
	exit 0
fi

# Main
if [ x"$PASSWD" = x'' ]; then
	echo -n '[sudo] password via SSH: '
	stty -echo
	read PASSWD
	stty echo
	echo ''
else
	NORMALIZED_ARGS=()
	REMOVE_ELEMENT='false'
	for i in $ARGS; do
		if [ x"$i" = x'-P' ]; then
			REMOVE_ELEMENT='true'
		elif [ x"$REMOVE_ELEMENT" = x'true' ]; then
			REMOVE_ELEMENT='false'
		else
			NORMALIZED_ARGS+=("$i")
		fi
	done
	ARGS="${NORMALIZED_ARGS[@]}"
fi

DSH_COMMAND="dsh -i -c -r ssh $ARGS"
echo "DSH_COMMAND: ${DSH_COMMAND}"
echo $PASSWD | $DSH_COMMAND
exit $?
