#!/bin/bash -
#===============================================================================
#
#          FILE:  sendscript
#
#         USAGE:  sendscript <TARGET or hostname>
#                 [-p|-o|nosave|nohostname|debug|-s <directory>|-u <username>|-i <ssh-key>]
#
#   DESCRIPTION:  Send shell command or script to hosts.
#
#       OPTIONS:  <TARGET or hostname> is start by "all" or "set"
#
#   REQUIREMENT:  1. Config file sendscript.conf
#                 2. /etc/hosts
#                 3. sendscript.alias (optional)
#
#         NOTES:  Use stdin is better.
#        AUTHOR:  rickz (Rick Zhang), xlrickz@gmail.com
#       COMPANY:  X-LEGEND Entertainment Corp.
#       CREATED:  Wed Jan 19 11:40:26 CST 2011
#      REVISION:  7.0
#===============================================================================
#set -o nounset                              # Treat unset variables as an error
set -m                                      # Enable job control

[ "$1" == "" ] && exec echo "Usage: $0 <TARGET or hostname> [-p|-o|nosave|nohostname|pesudo-tty|debug|-s <directory>|-u <username>|-i <ssh-key>]

TARGET type:
all
   gds
   sat
   ms
   ws
   db
   gamedb
   server
setX (X is \"set number\")
    sat
    ms
    ws
    gds
    db
    server

use \"$0 -h\" to get the TARGET example list.

Arguments:
 -p             Parallel mode
 -o             Parallel run and output AT ONCE to STDOUT after execute
 -s <directory>	Separate output to files by hostname into specify directory
 -u <username>	Specify the username to login with ssh
 -i <ssh-key>	Select a ssh private key file
 nosave		Dont save the script to /tmp/sendscript/\$TIME_NOW
 nohostname	Dont show the hostname to the output
 pesudo-tty	Force pseudo-tty
 sortbytime	Sort the log by time for the output
 debug		Print debug messages

Alias file:
You can use any alias you want in the file sendscript.alias, format:
KEY=\"STRING\"
"

# Check the config file exist
[ -f $0.conf ] || exec echo "Error: Cannot find $0.conf" >&2

# Setting the virables
TARGET="$1"
SETNUM="$(sed 's/[^0-9]//g' <<< "$TARGET")"
TIME_NOW="$(date +%Y%m%dT%H%M%S.%N)"
SSH_OPT=""

# Load the hosts naming from config file
source $0.conf

# For user who use Ctrl will call ~/.gamerc every time when a script start to run.
# This method will overwrite /etc/hosts. If sendscript reading a hosts file which
# still writing, a "Host not found" will occurs.
# So, here we made it force to make sure twice the hosts is not on change.
until [ "$HOSTS_IS_OKAY" == "1" ] ; do
   HOSTS_TIMESTAMP="$(date +%s.%N)"
   [ "$(cat /etc/hosts > /tmp/hosts.$HOSTS_TIMESTAMP ; md5sum /tmp/hosts.$HOSTS_TIMESTAMP;sleep 0.015)" == \
     "$(sleep 0.015;cat /etc/hosts > /tmp/hosts.$HOSTS_TIMESTAMP ; md5sum /tmp/hosts.$HOSTS_TIMESTAMP)" ] \
   && HOSTS_IS_OKAY="1" \
   || HOSTS_IS_OKAY="0"
   [ "$HOSTS_IS_OKAY" == "1" ] \
   && HOSTS_TEMP_FILE="/tmp/hosts.$HOSTS_TIMESTAMP" \
   || rm -f /tmp/hosts.$HOSTS_TIMESTAMP
done

# Remove the hosts temp file after 5 seconds from now
(sleep 5 ; rm -f $HOSTS_TEMP_FILE)&
disown

# Arguments
grep -iq sortbytime <<< "$*" && POSTCMD1=" sort -t , +1 -2 " || POSTCMD1="cat"
grep -iq debug <<< "$*"      && DEBUG=1
grep -iq -- -i <<< "$*"      && SSH_OPT=" $SSH_OPT -i $(awk -F" -i " '{print $2}' <<< "$*"|awk '{print $1}')"
grep -iq pesudo-tty <<< "$*" && SSH_OPT=" $SSH_OPT -t "
grep -iq -- -u <<< "$*"      && LOGINUSER="$(awk -F" -u " '{print $2}' <<< "$*"|awk '{print $1}')" || LOGINUSER=$(whoami)

# Colorize
function colorize() {
# Colorize stream editor by Rickz <iamrickz@gmail.com>
#                                       21:50, 2007/10/03.
FG="$1" ; BG="$2" ; EF1="$3" ; EF2="$4" ; EF3="$5"
echo "$3 $4 $5"|grep "1" 2>&1 > /dev/null && FG="39"
OLDFG="$FG";case "$FG" in
        black)  FG="30";;
        red)    FG="31";;
        green)  FG="32";;
        yellow) FG="33";;
        blue)   FG="34";;
        magenta)FG="35";;
        purple) FG="35";;
        cyan)   FG="36";;
        white)  FG="37";;
        default)FG="39";;
esac;[ "$OLDFG" == "$FG" ] && FG="39"
OLDBG="$BG";case "$BG" in
        black)  BG="40";;
        red)    BG="41";;
        green)  BG="42";;
        yellow) BG="43";;
        blue)   BG="44";;
        magenta)BG="45";;
        purple) BG="45";;
        cyan)   BG="46";;
        white)  BG="47";;
        default)BG="49";;
esac;[ "$OLDBG" == "$BG" ] && BG="49"
[ "$EF3" != "" ] && exec sed "s/\(.*\)/\x1b\x5b$BG\x3b$FG\x3b\x31\x6d\x1b\x5b$EF1\x6d\x1b\x5b$EF2\x6d\x1b\x5b$EF3\x6d\1\x1b\x5b\x30\x6d/g" -
[ "$EF2" != "" ] && exec sed "s/\(.*\)/\x1b\x5b$BG\x3b$FG\x3b\x31\x6d\x1b\x5b$EF1\x6d\x1b\x5b$EF2\x6d\1\x1b\x5b\x30\x6d/g" -
[ "$EF1" != "" ] && exec sed "s/\(.*\)/\x1b\x5b$BG\x3b$FG\x3b\x31\x6d\x1b\x5b$EF1\x6d\1\x1b\x5b\x30\x6d/g" -
[ "$BG" != "" ] && exec sed "s/\(.*\)/\x1b\x5b$BG\x3b$FG\x3b\x31\x6d\1\x1b\x5b\x30\x6d/g" -
[ "$FG" != "" ] && exec sed "s/\(.*\)/\x1b\x5b0\x3b$FG\x3b\x31\x6d\1\x1b\x5b\x30\x6d/g" -
}

print_servername () {
   egrep -i -h "^$1[[:blank:]]|[[:blank:]]$1" "$HOSTS_TEMP_FILE" "$HOSTS_FILE" 2> /dev/null |sed "s/^[0-9\.]*[[:blank:]]//g;s/ *$//g;s/ /_/g"|head -1
}

# Get IPs from $HOSTS_TEMP_FILE
if grep -qi "^all" <<< "$TARGET" ; then
	# For all*
        if grep -qi "patch$" <<< "$TARGET" ; then
                HOSTS="$(sed -n '/BELOW/,/ABOVE/p' "$HOSTS_TEMP_FILE"|grep "^[0-9]"|egrep "$HOSTS_ALL_PATCH"|awk '{print $1}')"
        elif grep -qi "^allall$" <<< "$TARGET" ; then
                HOSTS="$(sed -n '/BELOW/,/ABOVE/p' "$HOSTS_TEMP_FILE"|grep "^[0-9]"|awk '{print $1}')"
        elif grep -qi "gamedb$" <<< "$TARGET" ; then
                HOSTS="$(sed -n '/BELOW/,/ABOVE/p' "$HOSTS_TEMP_FILE"|grep "^[0-9]"|egrep "$HOSTS_ALL_GAMEDB"|awk '{print $1}')"
        elif grep -qi "worlddb$" <<< "$TARGET" ; then
                HOSTS="$(sed -n '/BELOW/,/ABOVE/p' "$HOSTS_TEMP_FILE"|grep "^[0-9]"|egrep "$HOSTS_ALL_WORLDDB"|awk '{print $1}')"
        elif grep -qi "gds$" <<< "$TARGET" ; then
                HOSTS="$(sed -n '/BELOW/,/ABOVE/p' "$HOSTS_TEMP_FILE"|grep "^[0-9]"|egrep "$HOSTS_ALL_GDS"|awk '{print $1}')"
        elif grep -qi "ms$" <<< "$TARGET" ; then
                HOSTS="$(sed -n '/BELOW/,/ABOVE/p' "$HOSTS_TEMP_FILE"|grep "^[0-9]"|egrep "$HOSTS_ALL_MS"|awk '{print $1}')"
        elif grep -qi "ws$" <<< "$TARGET" ; then
                HOSTS="$(sed -n '/BELOW/,/ABOVE/p' "$HOSTS_TEMP_FILE"|grep "^[0-9]"|egrep "$HOSTS_ALL_WS"|awk '{print $1}')"
        elif grep -qi "whs$" <<< "$TARGET" ; then
                HOSTS="$(sed -n '/BELOW/,/ABOVE/p' "$HOSTS_TEMP_FILE"|grep "^[0-9]"|egrep "$HOSTS_ALL_WHS"|awk '{print $1}')"
        elif grep -qi "chats$" <<< "$TARGET" ; then
                HOSTS="$(sed -n '/BELOW/,/ABOVE/p' "$HOSTS_TEMP_FILE"|grep "^[0-9]"|egrep "$HOSTS_ALL_CHATS"|awk '{print $1}')"
        elif grep -qi "ranks$" <<< "$TARGET" ; then
                HOSTS="$(sed -n '/BELOW/,/ABOVE/p' "$HOSTS_TEMP_FILE"|grep "^[0-9]"|egrep "$HOSTS_ALL_RANKS"|awk '{print $1}')"
        elif grep -qi "societys$" <<< "$TARGET" ; then
                HOSTS="$(sed -n '/BELOW/,/ABOVE/p' "$HOSTS_TEMP_FILE"|grep "^[0-9]"|egrep "$HOSTS_ALL_SOCIETYS"|awk '{print $1}')"
        elif grep -qi "db$" <<< "$TARGET" ; then
                HOSTS="$(sed -n '/BELOW/,/ABOVE/p' "$HOSTS_TEMP_FILE"|grep "^[0-9]"|egrep "$HOSTS_ALL_DB"|awk '{print $1}')"
        elif grep -qi "^allserver$" <<< "$TARGET" ; then
                HOSTS="$(sed -n '/BELOW/,/ABOVE/p' "$HOSTS_TEMP_FILE"|grep "^[0-9]"|egrep "$HOSTS_ALL_SERVER"|awk '{print $1}')"
        elif grep -qi "^all$" <<< "$TARGET" ; then
                HOSTS="$(sed -n '/BELOW/,/ABOVE/p' "$HOSTS_TEMP_FILE"|grep "^[0-9]"|egrep "$HOSTS_ALL"|awk '{print $1}')"
        else
                exec echo "Error: Wrong target specified: $TARGET" >&2
        fi
elif grep -qi "^set" <<< "$TARGET" ; then
	# For set*
        if grep -qi "^set$SETNUM$" <<< "$TARGET" ; then
                HOSTS="$(sed -n '/BELOW/,/ABOVE/p' "$HOSTS_TEMP_FILE"|grep "^[0-9]"|egrep "$HOSTS_SET"|awk '{print $1}')"
        elif grep -qi "set$SETNUM"db <<< "$TARGET" ; then
                HOSTS="$(sed -n '/BELOW/,/ABOVE/p' "$HOSTS_TEMP_FILE"|grep "^[0-9]"|egrep "$HOSTS_SET_DB"|awk '{print $1}')"
        elif grep -qi "set$SETNUM"gamedb <<< "$TARGET" ; then
                HOSTS="$(sed -n '/BELOW/,/ABOVE/p' "$HOSTS_TEMP_FILE"|grep "^[0-9]"|egrep "$HOSTS_SET_GAMEDB"|awk '{print $1}')"
        elif grep -qi "set$SETNUM"worlddb <<< "$TARGET" ; then
                HOSTS="$(sed -n '/BELOW/,/ABOVE/p' "$HOSTS_TEMP_FILE"|grep "^[0-9]"|egrep "$HOSTS_SET_WORLDDB"|awk '{print $1}')"
        elif grep -qi "set$SETNUM"gds <<< "$TARGET" ; then
                HOSTS="$(sed -n '/BELOW/,/ABOVE/p' "$HOSTS_TEMP_FILE"|grep "^[0-9]"|egrep "$HOSTS_SET_GDS"|awk '{print $1}')"
        elif grep -qi "set$SETNUM"ms <<< "$TARGET" ; then
                HOSTS="$(sed -n '/BELOW/,/ABOVE/p' "$HOSTS_TEMP_FILE"|grep "^[0-9]"|egrep "$HOSTS_SET_MS"|awk '{print $1}')"
        elif grep -qi "set$SETNUM"ws <<< "$TARGET" ; then
                HOSTS="$(sed -n '/BELOW/,/ABOVE/p' "$HOSTS_TEMP_FILE"|grep "^[0-9]"|egrep "$HOSTS_SET_WS"|awk '{print $1}')"
        elif grep -qi "set$SETNUM"whs <<< "$TARGET" ; then
                HOSTS="$(sed -n '/BELOW/,/ABOVE/p' "$HOSTS_TEMP_FILE"|grep "^[0-9]"|egrep "$HOSTS_SET_WHS"|awk '{print $1}')"
        elif grep -qi "set$SETNUM"chats <<< "$TARGET" ; then
                HOSTS="$(sed -n '/BELOW/,/ABOVE/p' "$HOSTS_TEMP_FILE"|grep "^[0-9]"|egrep "$HOSTS_SET_CHATS"|awk '{print $1}')"
        elif grep -qi "set$SETNUM"ranks <<< "$TARGET" ; then
                HOSTS="$(sed -n '/BELOW/,/ABOVE/p' "$HOSTS_TEMP_FILE"|grep "^[0-9]"|egrep "$HOSTS_SET_RANKS"|awk '{print $1}')"
        elif grep -qi "set$SETNUM"societys <<< "$TARGET" ; then
                HOSTS="$(sed -n '/BELOW/,/ABOVE/p' "$HOSTS_TEMP_FILE"|grep "^[0-9]"|egrep "$HOSTS_SET_SOCIETYS"|awk '{print $1}')"
        elif grep -qi "set$SETNUM"server <<< "$TARGET" ; then
                HOSTS="$(sed -n '/BELOW/,/ABOVE/p' "$HOSTS_TEMP_FILE"|grep "^[0-9]"|egrep "$HOSTS_SET_SERVER"|awk '{print $1}')"
        else
                exec echo "Error: Wrong set specified: $TARGET" >&2
        fi
else
	# Standalong host
	HOSTS="$(egrep -i "[[:blank:]]$TARGET$|[[:blank:]]$TARGET[[:blank:]]" "$HOSTS_TEMP_FILE"|awk '{print $1}')"
	[ "$(grep -i "[[:blank:]]$TARGET$|[[:blank:]]$TARGET[[:blank:]]" "$HOSTS_TEMP_FILE"|awk '{print $1}'|wc -l)" -gt 1 ] && HOSTS=""
fi

# if got no host, show help
if [ -z "$HOSTS" ] ; then

        echo "Error: Host not found: $TARGET" >&2
        echo >&2
        echo "Target example:" >&2

	SETNUM=1
	source $0.conf

        #example list
        echo "          " > /tmp/hosts-sendscript
        sed -n '/BELOW/,/ABOVE/p' "$HOSTS_TEMP_FILE"|grep "^[0-9]"|tr '[[:blank:]]' '\n'|grep "[A-Z]"|\
        sed 's/$/         /g;s/^\(..........\).*/\1/g' | sort >> /tmp/hosts-sendscript

        echo allall > /tmp/hosts-allall ; for i in `cat /tmp/hosts-sendscript`;do
                sed -n '/BELOW/,/ABOVE/p' "$HOSTS_TEMP_FILE"|grep "^[0-9]"|grep -q "$i" && echo v || echo
        done >> /tmp/hosts-allall

        echo all > /tmp/hosts-all ; for i in `cat /tmp/hosts-sendscript`;do
                sed -n '/BELOW/,/ABOVE/p' "$HOSTS_TEMP_FILE"|grep "^[0-9]"|egrep "$HOSTS_ALL"|grep -q "$i" && echo v || echo
        done >> /tmp/hosts-all

        echo allsat > /tmp/hosts-allsat ; for i in `cat /tmp/hosts-sendscript`;do
                sed -n '/BELOW/,/ABOVE/p' "$HOSTS_TEMP_FILE"|grep "^[0-9]"|egrep "$HOSTS_ALL_SAT"|grep -q "$i" && echo v || echo
        done >> /tmp/hosts-allsat

        echo allms > /tmp/hosts-allms ; for i in `cat /tmp/hosts-sendscript`;do
                sed -n '/BELOW/,/ABOVE/p' "$HOSTS_TEMP_FILE"|grep "^[0-9]"|egrep "$HOSTS_ALL_MS"|grep -q "$i" && echo v || echo
        done >> /tmp/hosts-allms

        echo allws > /tmp/hosts-allws ; for i in `cat /tmp/hosts-sendscript`;do
                sed -n '/BELOW/,/ABOVE/p' "$HOSTS_TEMP_FILE"|grep "^[0-9]"|egrep "$HOSTS_ALL_WS"|grep -q "$i" && echo v || echo
        done >> /tmp/hosts-allws

        echo allgds > /tmp/hosts-allgds ; for i in `cat /tmp/hosts-sendscript`;do
                sed -n '/BELOW/,/ABOVE/p' "$HOSTS_TEMP_FILE"|grep "^[0-9]"|egrep "$HOSTS_ALL_GDS"|grep -q "$i" && echo v || echo
        done >> /tmp/hosts-allgds

        echo alldb > /tmp/hosts-alldb ; for i in `cat /tmp/hosts-sendscript`;do
                sed -n '/BELOW/,/ABOVE/p' "$HOSTS_TEMP_FILE"|grep "^[0-9]"|egrep "$HOSTS_ALL_DB"|grep -q "$i" && echo v || echo
        done >> /tmp/hosts-alldb

        echo set1 > /tmp/hosts-set1 ; for i in `cat /tmp/hosts-sendscript`;do
                sed -n '/BELOW/,/ABOVE/p' "$HOSTS_TEMP_FILE"|grep "^[0-9]"|egrep "$HOSTS_SET"|grep -q "$i" && echo v || echo
        done >> /tmp/hosts-set1

        echo set1sat > /tmp/hosts-set1sat ; for i in `cat /tmp/hosts-sendscript`;do
                sed -n '/BELOW/,/ABOVE/p' "$HOSTS_TEMP_FILE"|grep "^[0-9]"|egrep "$HOSTS_SET_SAT"|grep -q "$i" && echo v || echo
        done >> /tmp/hosts-set1sat

        echo set1ms > /tmp/hosts-set1ms ; for i in `cat /tmp/hosts-sendscript`;do
                sed -n '/BELOW/,/ABOVE/p' "$HOSTS_TEMP_FILE"|grep "^[0-9]"|egrep "$HOSTS_SET_MS"|grep -q "$i" && echo v || echo
        done >> /tmp/hosts-set1ms

        echo set1wz > /tmp/hosts-set1wz ; for i in `cat /tmp/hosts-sendscript`;do
                sed -n '/BELOW/,/ABOVE/p' "$HOSTS_TEMP_FILE"|grep "^[0-9]"|egrep "$HOSTS_SET_WZ"|grep -q "$i" && echo v || echo
        done >> /tmp/hosts-set1wz

        echo set1gds > /tmp/hosts-set1gds ; for i in `cat /tmp/hosts-sendscript`;do
                sed -n '/BELOW/,/ABOVE/p' "$HOSTS_TEMP_FILE"|grep "^[0-9]"|egrep "$HOSTS_SET_GDS"|grep -q "$i" && echo v || echo
        done >> /tmp/hosts-set1gds

        echo set1db > /tmp/hosts-set1db ; for i in `cat /tmp/hosts-sendscript`;do
                sed -n '/BELOW/,/ABOVE/p' "$HOSTS_TEMP_FILE"|grep "^[0-9]"|egrep "$HOSTS_SET_GAMEDB"|grep -q "$i" && echo v || echo
        done >> /tmp/hosts-set1db

        paste /tmp/hosts-sendscript /tmp/hosts-allall /tmp/hosts-all /tmp/hosts-allsat /tmp/hosts-allms /tmp/hosts-allws /tmp/hosts-allgds /tmp/hosts-alldb /tmp/hosts-set1 /tmp/hosts-set1sat /tmp/hosts-set1ms /tmp/hosts-set1wz /tmp/hosts-set1gds /tmp/hosts-set1db >&2
        rm -f /tmp/hosts-sendscript /tmp/hosts-allall /tmp/hosts-all /tmp/hosts-allsat /tmp/hosts-allms /tmp/hosts-allws /tmp/hosts-allgds /tmp/hosts-alldb /tmp/hosts-set1 /tmp/hosts-set1sat /tmp/hosts-set1ms /tmp/hosts-set1wz /tmp/hosts-set1gds /tmp/hosts-set1db
        exit
fi

# Get alias list
alias2sed () {
   [ -f $0.alias ] && eval $(sed 's/\*/\\\*/g;s/?/\\\?/g;s/\$/\\\$/g' $0.alias)
   [ -f $0.alias ] \
   && for i in `cat $0.alias | awk -F= '{print $1}'`;do
	echo "s&$i&$(eval echo \$$i)&g"
   done \
   || echo "s&nothing_else&nothing&g"
}

[ "$DEBUG" == "1" ] && echo "Input from stdin(end by Ctrl+d, exit by Ctrl+c):"
mkdir -p /tmp/sendscript > /dev/null 2>&1
chmod 777 /tmp/sendscript/ > /dev/null 2>&1
cat >> /tmp/sendscript/$TIME_NOW
[ "$DEBUG" == "1" ] && echo -n "Save cmds to /tmp/sendscript/$TIME_NOW ... " >&2
grep -iq pesudo-tty <<< "$*" || echo "exit" >> /tmp/sendscript/$TIME_NOW
[ "$DEBUG" == "1" ] && echo "OK" >&2

if [ "$DEBUG" == "1" ] ;then
	echo "DEBUG: alias2sed:"
	alias2sed
	echo
	echo "DEBUG: script result:"
	sed -e "$(alias2sed)" /tmp/sendscript/$TIME_NOW
	echo
fi

# IPs to connect
for IP in $HOSTS ;do
   if grep -iq -- "-s" <<< "$*" ; then

	# Save to directory mode
	SAVE_TO_DIRECTORY="$(awk -F" -s " '{print $2}' <<< "$*"|awk '{print $1}')"
	OUTPUT_FILE="$SAVE_TO_DIRECTORY/$(print_servername $IP)-output"
	[ -z "$SAVE_TO_DIRECTORY" ] && exec echo "Error: No directory name specified."
	mkdir -p "$SAVE_TO_DIRECTORY" || exec echo "Error: Directory creation failed."
        if grep -iq -- "-p"  <<< "$*" ; then
		if ! grep -iq nohostname <<< "$*" ; then
	                print_servername $IP | colorize yellow black >&2
		fi
                if grep -iq pesudo-tty <<< "$*" ; then
			ssh $SSH_OPT -o StrictHostKeyChecking=no $LOGINUSER@$IP $(sed -e "$(alias2sed)" /tmp/sendscript/$TIME_NOW) > $OUTPUT_FILE \
			|| ( RETURN="$?" ; [ "$SHOW_RETURN_WARNING" == "1" ] && echo "Warning: Return is $RETURN on $(print_servername $IP)" | colorize red black >&2 ) &
		else
			sed -e "$(alias2sed)" /tmp/sendscript/$TIME_NOW \
			| ssh $SSH_OPT -o StrictHostKeyChecking=no $LOGINUSER@$IP 'cat|sh' > $OUTPUT_FILE \
			|| ( RETURN="$?" ; [ "$SHOW_RETURN_WARNING" == "1" ] && echo "Warning: Return is $RETURN on $(print_servername $IP)" | colorize red black >&2 ) &
		fi
        else #if grep -iq -- "-p"  <<< "$*" ; then
		if ! grep -iq nohostname <<< "$*" ; then
	                [ -t 1 ] || print_servername $IP | colorize yellow black >&2
		fi
                if grep -iq pesudo-tty <<< "$*" ; then
			ssh $SSH_OPT -o StrictHostKeyChecking=no $LOGINUSER@$IP $(sed -e "$(alias2sed)" /tmp/sendscript/$TIME_NOW) > $OUTPUT_FILE \
			|| ( RETURN="$?" ; [ "$SHOW_RETURN_WARNING" == "1" ] && echo "Warning: Return is $RETURN on $(print_servername $IP)" | colorize red black >&2 )
		else
			sed -e "$(alias2sed)" /tmp/sendscript/$TIME_NOW \
			| ssh $SSH_OPT -o StrictHostKeyChecking=no $LOGINUSER@$IP 'cat|sh' > $OUTPUT_FILE \
			|| ( RETURN="$?" ; [ "$SHOW_RETURN_WARNING" == "1" ] && echo "Warning: Return is $RETURN on $(print_servername $IP)" | colorize red black >&2 )
		fi
       fi
   elif grep -iq -- "-o" <<< "$*" ; then #if grep -iq -- "-s" <<< "$*" ; then

	# Output at once mode
	SAVE_TO_DIRECTORY="sendscript-o-$TIME_NOW.dir"
	OUTPUT_FILE="$SAVE_TO_DIRECTORY/$(print_servername $IP)-output"
	mkdir -p "$SAVE_TO_DIRECTORY" || exec echo "Error: Directory creation failed."
        if grep -iq pesudo-tty <<< "$*" ; then
		ssh $SSH_OPT -o StrictHostKeyChecking=no $LOGINUSER@$IP $(sed -e "$(alias2sed)" /tmp/sendscript/$TIME_NOW) > $OUTPUT_FILE \
		|| ( RETURN="$?" ; [ "$SHOW_RETURN_WARNING" == "1" ] && echo "Warning: Return is $RETURN on $(print_servername $IP)" | colorize red black >&2 ) &
	else
		sed -e "$(alias2sed)" /tmp/sendscript/$TIME_NOW \
		| ssh $SSH_OPT -o StrictHostKeyChecking=no $LOGINUSER@$IP 'cat|sh' > $OUTPUT_FILE \
		|| ( RETURN="$?" ; [ "$SHOW_RETURN_WARNING" == "1" ] && echo "Warning: Return is $RETURN on $(print_servername $IP)" | colorize red black >&2 ) &
	fi

   else #if grep -iq -- "-o" <<< "$*" ; then

	# Normal output mode
        if grep -iq -- "-p"  <<< "$*" ; then
		if ! grep -iq nohostname <<< "$*" ; then
	                [ -t 1 ] && print_servername $IP | colorize yellow black >&2 \
	                || print_servername "$IP"
	                print_servername $IP | colorize yellow black >&2
		fi
		if grep -iq pesudo-tty <<< "$*" ; then
			ssh $SSH_OPT -o StrictHostKeyChecking=no $LOGINUSER@$IP $(sed -e "$(alias2sed)" /tmp/sendscript/$TIME_NOW) \
			|| ( RETURN="$?" ; [ "$SHOW_RETURN_WARNING" == "1" ] && echo "Warning: Return is $RETURN on $(print_servername $IP)" | colorize red black >&2 ) &
		else
			sed -e "$(alias2sed)" /tmp/sendscript/$TIME_NOW \
			| ssh $SSH_OPT -o StrictHostKeyChecking=no $LOGINUSER@$IP 'cat|sh' \
			|| ( RETURN="$?" ; [ "$SHOW_RETURN_WARNING" == "1" ] && echo "Warning: Return is $RETURN on $(print_servername $IP)" | colorize red black >&2 ) &
		fi
        else #if grep -iq -- "-p"  <<< "$*" ; then
		if ! grep -iq nohostname <<< "$*" ; then
	                [ -t 1 ] || print_servername $IP | colorize yellow black >&2
	                [ -t 1 ] && print_servername $IP | colorize yellow black \
	                || print_servername "$IP"
		fi
		if grep -iq pesudo-tty <<< "$*" ; then
			ssh $SSH_OPT -o StrictHostKeyChecking=no $LOGINUSER@$IP $(sed -e "$(alias2sed)" /tmp/sendscript/$TIME_NOW) \
			|| ( RETURN="$?" ; [ "$SHOW_RETURN_WARNING" == "1" ] && echo "Warning: Return is $RETURN on $(print_servername $IP)" | colorize red black >&2 )
		else
			sed -e "$(alias2sed)" /tmp/sendscript/$TIME_NOW \
			| ssh $SSH_OPT -o StrictHostKeyChecking=no $LOGINUSER@$IP 'cat|sh' \
			|| ( RETURN="$?" ; [ "$SHOW_RETURN_WARNING" == "1" ] && echo "Warning: Return is $RETURN on $(print_servername $IP)" | colorize red black >&2 )
		fi
	fi

   fi #if grep -iq -- "-o" <<< "$*" ; then
done

wait

# Clean up the files that size zero and sort by time
if egrep -iq -- "-s|-o" <<< "$*" ; then

   # Delete files size zero
   # if egrep -iq -- "-s" <<< "$*" ; then
   #	for OUTPUT_FILE in $SAVE_TO_DIRECTORY/* ; do
   #		[ -s "$OUTPUT_FILE" ] || rm -f "$OUTPUT_FILE"
   #	done
   # fi

   # Sort by time
   if grep -iq sortbytime <<< "$*" ; then
	cat $SAVE_TO_DIRECTORY/* 2> /dev/null | sort -t , +1 -2 > sortedbytime.$SAVE_TO_DIRECTORY
	mv sortedbytime.$SAVE_TO_DIRECTORY $SAVE_TO_DIRECTORY/sortedbytime
   fi

   # Output at once
   if grep -iq -- "-o" <<< "$*" ; then
	[ -e $SAVE_TO_DIRECTORY/sortedbytime ] \
	&& cat $SAVE_TO_DIRECTORY/sortedbytime \
	|| cat $SAVE_TO_DIRECTORY/* 2> /dev/null
   fi
fi

# Remove files
[ "$NOSAVE_AS_DEFAULT" == "1" ] && rm -rf /tmp/sendscript/$TIME_NOW sendscript-o-*
grep -iq nosave <<< "$*" && rm -rf /tmp/sendscript/$TIME_NOW sendscript-o-*

# Always return true if we use -o option
grep -iq -- "-o" <<< "$*" && true
