#!/bin/bash
#
#       Copyright (c) 2003 ParTec AG Karlsruhe
#       All rights reserved.
# @author
#       Jens Hauke <hauke@par-tec.de>
#
# (Friday noon vision of a parallel shell :-)
#
# The configfile could look like this:
#${HOME}/.psh.d/default:
#-n carla[1-4]
#node carla14
#max 16

D_CONFIG_D="${HOME}/.psh.d"
D_CONFIG="${D_CONFIG_D}/default"
D_RCMD="ssh -x"
D_MAXRCMD=32
D_DIFFCMD="diff -q"
D_AUTOCD="cd ${PWD/#${HOME}/~} &&"
TMPTEMPLATE="/tmp/pshout.XXXXXX"

############################
# Use mpiexec/pssh if available?

#if [ -f "/opt/parastation/bin/mpiexec" ] ; then
#    PARASTATIONSTART="/opt/parastation/bin/mpiexec"
#    $PARASTATIONSTART --checkup 1>/dev/null 2>&1 \
#    && USE_MPIEXEC="TRUE" && D_RCMD="$PARASTATIONSTART -A -N"
#else
#    PARASTATIONSTART="/opt/parastation/bin/pssh"
#fi

#if [ -x "${PARASTATIONSTART}" ] ; then
#    D_RCMD="${PARASTATIONSTART}";
#fi

#############################
# create a default template 
if [ ! -e "${D_CONFIG}" ] ; then
    read -n 1 -p "Create ${D_CONFIG} [y/N]? " q
    echo
    case "$q" in
    y|Y)
        mkdir -p ${D_CONFIG_D}
        cat >> ${D_CONFIG} <<EOF
## psh defaults
## uncomment all options you need...

## default nodelist:
# node nodename[01-16]

## default remote command:
# rcmd pssh
# rcmd ssh -x

## dont start more than 1 remote shell at the same time?
# max 1

## be always verbose ?
# verbose

EOF
        ;;
    esac
fi

####################################################
# alternative default? (hostname%dx,hostnamex,default)
tmp=$(hostname -s)
if [ -e "${D_CONFIG_D}/${tmp}" ] ; then
    D_CONFIG=${D_CONFIG_D}/${tmp}
else 
    tmp=${tmp//[0-9]/}
    if [ -e "${D_CONFIG_D}/${tmp}" ] ; then
	D_CONFIG=${D_CONFIG_D}/${tmp}
    fi
fi

#######################

function help
{
cat <<EOF
Usage: psh [OPTION]... command
       psh [OPTION]... -sync filename...
       psh [OPTION]... -sync dirname...

Options:
   -g|-group {group}      : Use group defined in $D_CONFIG_D 
                            (default "default")
   -c|-configfile {cfile} : Set configuration file 
                            (default "$D_CONFIG").
   -n|-node {node,...}    : Append {node} to nodelist.
   -x|-xnode {node,...}   : Exclude {node} from nodelist.
   -s|-sync               : copy one file to all nodes.
   -rcmd {rcmd}           : set remote shell (default "$D_RCMD").
   -max {nmax}            : dont start more than {nmax} remote shells
                            at the same time (default $D_MAXRCMD).
   -diff {cmd}            : Program which compares the outputs 
                            (default "$D_DIFFCMD")
   -autocd                : remote dir (default "cd \${PWD/\${HOME}/~};")
                            use -autocd "" to disable autocd.
   -v|-verbose            : Be verbose
   -h|-help               : help
EOF
}

function parse()
{
#    echo Parse "$*"
    case "$1" in
	-g|${prearg}group)
            CONFIG="${CONFIG_D}/$2"
	    nopts=2
	    ;;
	-c|${prearg}configfile) 
	    CONFIG="$2"
	    nopts=2
	    ;;
	-n|${prearg}node)
	    if [ "${cmd_line_nodes-0}" = 0 ];then
		NODES=(${NODES[*]} $(nameexpand "$2"))
		nopts=2
	    fi
	    ;;
	-s|-sync)
	    SYNC=1
	    nopts=1
	    ;;
	${prearg}rcmd)
	    RCMD=${RCMD-"$2"}
	    nopts=2
	    ;;
	${prearg}max)
	    MAXRCMD=${MAXRCMD-"$2"}
	    nopts=2
	    ;;
	${prearg}diff)
	    DIFFCMD=${DIFFCMD-"$2"}
	    nopts=2
	    ;;
	-x|${prearg}xnode)
	    XNODES=(${XNODES[*]} $(nameexpand "$2"))
	    nopts=2
	    ;;
	${prearg}autocd)
	    AUTOCD=${AUTOCD-"$2"}
	    nopts=2
	    ;;
	-v|${prearg}verbose)
	    VERBOSE=1
	    nopts=1
	    ;;
	-h|${prearg}help)
	    help
	    exit 1
	    ;;
	${prearg}#*) # comment
	    nopts=1
	    ;;
	${prearg}*)
	    echo "$optsource : unknown option \"$1\"."
	    help
	    exit 1;
	    ;;
	*)
	    nopts=0;
    esac
}

function cleanup
{
#    echo Cleanup called
    if [ x"$TMPFILES" != x ]; then
	rm $TMPFILES
    fi
}

#
# merge hostnames (e.g. host001 host002 to host[001-002])
#
function namemerge()
{
    echo "$*"|awk '
BEGIN{ RS=" " }
function nprint(key1,key2)
{
   result="";
   elements=0;
   delete f;
   for (j = 0; j < hostmcnt[key1,key2]; j++) {
       f[hostmno[key1,key2,j] + 0]= hostmno[key1,key2,j];
   }

   while (1) {
       min = 999999;
       for ( j in f ) {
           if (j + 0 < min) min = j + 0; # force min to be nummeric!
       }
       if ( min == 999999 ) break;
       j=min;
       from=f[j];
       until=f[j];
       delete f[j];
       while ((j + 1) in f) {
           j++;
           until=f[j];
           delete f[j];
       }

       if (elements++) result=result",";
       if (from + 0 == until + 0) {
           result=result from;
       } else if (from + 1 == until + 0) {
           result=result from "," until;
           elements++;
       } else {
           result=result from "-" until;
           elements++;
       }
   } 
   if (elements == 1) {
       return result;
   } else {
       return "[" result "]";
   }
}


{
   hostname=$1;

   match(hostname, "([^0-9]*)([0-9]*)(.*)", s);
#   print $1," 1:"s[0]" 2:"s[1]" 3:"s[2]" 4:"s[3];
   # ToDo search rightmost match of digit, not leftmost
   bname=s[1] s[2]+0 s[3]
#   print "Bname: "bname
   if (!bnames[bname]) {
       bnames[bname]=1;
       hostm1[s[1],s[3]] = s[1];
       hostm3[s[1],s[3]] = s[3];
       cnt=hostmcnt[s[1],s[3]] * 1;
       hostmno[s[1],s[3],cnt] = s[2];
       hostmcnt[s[1],s[3]]++;
   } else {
       doubles=doubles", "hostname;
   }
}

END{
   _first=1;
   for (i in hostm1) {
       if (_first == 0) printf ", ";
       _first=0;
       printf "%s", hostm1[i] nprint(hostm1[i], hostm3[i]) hostm3[i];
   }
   print doubles;
}
'
}

function nameexpand()
{
    echo "$*"| awk '
BEGIN{ RS=" " }

function expand(name,pat)
{
    el = split(pat, sp, ",");
    for (i=1;i<=el;i++) {
      eel = split(sp[i], ssp, "-");
      if (eel<=1) { /* one or no value */
          x=name;
          sub("\\["pat"\\]",ssp[1],x);
          print x;
      } else { /* range */
          if (substr(ssp[1],1,1) == "0") {
              /* leading 0s */
              for (j = ssp[1] + 0; j <= ssp[2] + 0; j++) {
                  x=name;
                  sub("\\["pat"\\]",sprintf("%0"length(ssp[1])"d", j),x);
                  print x;
              } 
          } else {
              for (j = ssp[1] + 0; j <= ssp[2] + 0; j++) {
                  x=name;
                  sub("\\["pat"\\]",sprintf("%"length(ssp[1])"d", j),x);
                  print x;
              } 
           }
      }
    }
}

{
   hostname=$1;
   n = split(hostname, hs, ","); /* comma sep list */
   for (ii=1; ii<=n;ii++) {
       if (hs[ii] ~ /\[/ ) {
           h=hs[ii];
           while ((ii+1<=n) && !(h ~ /\]/)) {
               ii++;
               h=h","hs[ii]; /* merge splited [,]*/
           }
           match(h, "\\[([^[]*)\\]", s);
           if (s[0] != "") {
               expand(h, s[1]);
           } else {
               print h;
           }
       } else {
               print hs[ii];
       }
   }
}
'
}

#
# remove $1 from nodelist
#
function del_node()
{
    NODES=" ${NODES[*]} "
    NODES=(${NODES/" $1 "/" "})
}


#
# Just fetch SIGINT
#
function killcurrent
{
    echo kill $WAITFOR
}

#
# Wait until the next process ends and collect the exit code.
#
function ecollect
{
    ii=${#EXITCODES[*]}
    WAITFOR=${PIDS[$ii]}
    if [ "$VERBOSE" = 1 ];then
	echo "Wait for ${NODES[${#EXITCODES[*]}]} (pid ${PIDS[$ii]})"
    fi
    wait ${PIDS[$ii]}
    ec="$?"
    if [ "$ec" != "0" ]; then
	echo "Exit $ec" >> ${OUTPUTS[$ii]}
    fi
    EXITCODES=(${EXITCODES[*]} "$ec")
}

trap cleanup EXIT

CONFIG="$D_CONFIG"
CONFIG_D="$D_CONFIG_D"

#
# Parse commandline
#
optsource="Commandline"
prearg="-"
nopts=1
while [ $nopts != 0 ] ; do
    parse "$@"
    shift $nopts
done

#
# Read configuration
#
prearg=""
cmd_line_nodes="${#NODES[*]}"

if [ -f "${CONFIG}" ]; then
    line=0
    while read command opts; do
	line=$(( $line + 1 ))
	optsource="$CONFIG:$line"
	if [ ! -z "$command" ]; then
	    parse "$command" "$opts"
	fi
    done < "${CONFIG}"
fi

COMMAND="$*"

if [ x"$COMMAND" = x ];then
    if [ x"$SYNC" = x ]; then
	echo "Error: Missing command"
    else
	echo "Error: Missing filename"
    fi
    help
    exit 1
fi

if [ "${#NODES[*]}" = 0 ];then
    echo "Error: No nodes"
    help
    exit 1
fi

for((i = 0 ;i < ${#XNODES[*]} ;i++)); do
    del_node ${XNODES[$i]}
done


RCMD="${RCMD-$D_RCMD}"
MAXRCMD="${MAXRCMD-$D_MAXRCMD}"
DIFFCMD="${DIFFCMD-$D_DIFFCMD}"
AUTOCD="${AUTOCD-$D_AUTOCD}"

if [ "${SYNC}" = 1 ]; then
    FILELIST="$COMMAND"
    COMMAND="tar xvPf -";
    TARFILE=$(mktemp $TMPTEMPLATE)
    TMPFILES="$TMPFILES $TARFILE"
    echo "Prepare files for distribution:"
    tar cvPf "${TARFILE}" ${FILELIST}
    echo "Continue(y/n)?[n]"
    read c
    case "$c" in
	y|Y)
	;;
	*)
	    exit 1;
    esac
    INPUT="${TARFILE}"
else
    INPUT="/dev/null"
fi



if [ "$VERBOSE" = 1 ];then
cat <<EOF
CONFIG  ${D_CONFIG}
NODES   ${NODES[*]}
NODESSHORT $(namemerge ${NODES[*]})
RCMD    $RCMD
COMMAND $COMMAND
EOF
fi

## Use specal syntax for mpiexec
if [ "$USE_MPIEXEC" == "TRUE" ] ; then
    nodes=${NODES[*]}
    $RCMD "$nodes" $COMMAND
    exit 0
fi


trap killcurrent SIGINT

#
# Start remote jobs
#
for ((i = 0; i < ${#NODES[*]} ; i++)); do
    host=${NODES[$i]}
    OUTFILE=$(mktemp $TMPTEMPLATE)
    TMPFILES="$TMPFILES $OUTFILE"
    OUTPUTS=(${OUTPUTS[*]} ${OUTFILE})
    < "${INPUT}" $RCMD "$host" "$AUTOCD$COMMAND" > $OUTFILE 2>&1 &
    PIDS=(${PIDS[*]} $!)
    if [ "$VERBOSE" = 1 ];then
	echo "$RCMD $host $COMMAND"
    fi
    if [ $(($i + 1)) -ge "$MAXRCMD" ]; then
	ecollect
    fi
done

#
# Wait for finish
#
for ((i = ${#EXITCODES[*]}; i < ${#NODES[*]} ; i++)); do
    ecollect
done

#
# Merge outputs
#
for ((i = 0; i < ${#NODES[*]} ; i++)); do
    hosts=${NODES[$i]}
    if [ "${DISPLAYED[$i]}" != "1" ]; then
	# search for equal outputs
	for ((ii = $i + 1; ii < ${#NODES[*]} ; ii++)); do
	    if [ "${DISPLAYED[$ii]}" != "1" ]; then
      #	    echo Compare ${OUTPUTS[$i]} ${OUTPUTS[$ii]}
		if ${DIFFCMD} ${OUTPUTS[$i]} ${OUTPUTS[$ii]} > /dev/null; then
		    hosts="$hosts ${NODES[$ii]}"
		    DISPLAYED[$ii]="1";
		fi
	    fi
	done
	echo "=== $(namemerge $hosts)"
	cat ${OUTPUTS[$i]}
    fi
done

