#!/bin/sh

usage (){
    cat 1>&2 <<'EOF'
paargs -- wrapper for paexec
usage: paargs [OPTIONS]
OPTIONS:
  -h               display this help
  -V               display version

  -P <+num>        number of subprocesses to run
     <nodes>       list of nodes separated by space character
     <:filename>   filename containing a list of nodes, one node per line
  -t <transport>   set a transport program
  -c <command>     command with its arguments. By default, free arguments
                   are used for setting command and its arguments

  -I <replstr>     execute command for each task, replacing one
                   or more occurrences of replstr with the entire task
  -X               ignore calculator's stdout
  -f               flushes stdout after recieving an end-of-task signal
  -0               change paexec to expect NUL characters as separators
                   instead of newline

  -d               debug mode, for debugging only

  -Z <timeout>     passed directly to paexec
  -z               passed directly to paexec

  -m   s=<success> set an alternative for 'success' message
       f=<failure> set an alternative for 'failure' message
       F=<fatal>   set an alternative for 'fatal' message
       t=<EOT>     set an alternative for EOT marker
       d=<delimiter>    set the delimiter for -g mode,
                        no delimiter by default
       w=<weight>  set an alternative for 'weight:' marker

-P is a mandatory option
EOF
}

command='paexec -Cxleg -md='
version='1.1.3'

shquote (){
    __cmd=`printf '%s\n' "$1" | sed "s|'|'\\\\\''|g"`
    printf "%s\n" "'$__cmd'"
}

while getopts 0c:dfI:hm:P:t:VXzZ: f; do
    case "$f" in
	'?')
	    exit 1;;
	h)
	    usage
	    exit 0;;
	V)
	    echo "paargs $version written by Aleksey Cheusov"
	    exit 0;;
	P)
	    addon=$(shquote "$OPTARG")
	    command="$command -n$addon";;
	t)
	    addon=$(shquote "$OPTARG")
	    command="$command -t$addon";;
	X)
	    command="$command -X";;
	f)
	    command="$command -E";;
	m)
	    addon=$(shquote "$OPTARG")
	    command="$command -m$addon";;
	I)
	    addon=$(shquote "$OPTARG")
	    command="$command -J$addon";;
	0)
	    command="$command -0";;
	d)
	    command="$command -d";;
	Z)
	    addon=$(shquote "$OPTARG")
	    command="$command -w -Z$addon";;
	z)
	    command="$command -wz";;
	c)
	    command_specified=1
	    addon=$(shquote "$OPTARG")
	    command="$command -c$addon";;
    esac
done
shift `expr $OPTIND - 1`

if test -n "$command_specified"; then
    if test $# -ne 0; then
	echo 'paargs: extra arguments. Run paargs -h for details' 1>&2
	exit 1
    fi
else
    if test $# -eq 0; then
	echo 'paargs: missing arguments. Run paargs -h for details' 1>&2
	exit 1
    fi
fi

for fa in "$@"; do
    addon=$(shquote "$fa")
    command="$command $addon"
done

#echo $command 1>&2
eval "$command"
