#!/bin/ksh
# @(#) te.ksh 1.2 94/03/08
# 92/08/31 john@armory.com
# 92/09/10 added -p option to whence
# 92/10/16 Allow multiple ,-separated targets; added help
# 92/10/21 Added {}
# 93/08/02 Changed name to te to avoid conflict with to
# 94/03/08 Added -c option

name=${0##*/}

Usage=\
"Usage: 
$name target[,target,...] command [arg ...]
or
$name -c \"command [arg ...]\" target [target ...]"

typeset -i MinArgs=2

while getopts :hc: opt; do
    case $opt in
    h)
    echo \
"$name: execute commands on commands.
$Usage
Each target is searched for as a command in \$PATH and expanded into its
full filename.  command [arg ...] is then executed with the list of
filenames as additional arguments.
If one of the arguments is \"{}\", it is replaced with the list of
filenames and the filenames are not passed as additional arguments."
	exit 0
	;;
    c)
	Cmd=$OPTARG
	MinArgs=1
	;;
    +?)
	print -u2 "$name: options should not be preceded by a '+'."
	exit 1
	;;
    ?) 
	print -u2 "$name: $OPTARG: bad option.  Use -h for help."
	exit 1
	;;
    esac
done
 
# remove args that were options
let OPTIND=OPTIND-1
shift $OPTIND

if [ $# -lt MinArgs ]; then
    print -u2 "$Usage\nUse -h for help."
    exit
fi

typeset -i numtarg=0 CmdInd=0

if [ -z "$Cmd" ]; then
    targets=$1
    shift 1
    set -A command "$@"
    OFS=$IFS
    IFS=,
    set -- $targets
    IFS=$OFS
else
    set -A targets -- "$@"
    set -A command $Cmd
    set -- "${targets[@]}"
fi

for target; do
    file=`whence -p $target`
    if [ -z "$file" ]; then
	print -u2 "$target: not found"
    else
	targarr[numtarg]=$file
	let numtarg+=1
    fi
done
while [ CmdInd -lt ${#command[*]} ]; do
    if [ "${command[CmdInd]}" = {} ]; then
	command[CmdInd]="${targarr[*]}"
	exec "${command[@]}"
    fi
    let CmdInd+=1
done
[ numtarg -gt 0 ] && exec "${command[@]}" "${targarr[@]}"
