#!/bin/sh
#
# External STONITH module for lxha.
#
# Copyright (c) 2001-2014 Linx Technology Co.,Ltd. 
#

LXHA_COMMAND="/sbin/lxhacli "
REBOOT_COMMAND="11123 0 reset"
POWEROFF_COMMAND="11123 0 poweroff"


# Rewrite the hostlist to accept "," as a delimeter for hostnames too.
hostlist=`echo $hostlist | tr ',' ' '`

is_host_up() {
  for j in 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
  do
    if
      ping -w1 -c1 "$1" >/dev/null 2>&1
    then
      sleep 1
    else
      return 1
    fi
  done
  return 0
}


case $1 in
gethosts)
	for h in $hostlist ; do
		echo $h
	done
	exit 0
	;;
on)
	# Can't really be implemented because ssh cannot power on a system
	# when it is powered off.
	exit 1
	;;
off)
	# Shouldn't really be implemented because if ssh cannot power on a 
	# system, it shouldn't be allowed to power it off.
	exit 1
	;;
reset)
	h_target=`echo $2 | tr A-Z a-z`
	for h in $hostlist
	do
		h=`echo $h | tr A-Z a-z`
		[ "$h" != "$h_target" ] &&
            continue
          if
            case ${livedangerously} in
              [Yy]*)	is_host_up $h;;
	      *)	true;;
             esac
          then
	    $LXHA_COMMAND $2 $REBOOT_COMMAND  &
	    # Good thing this is only for testing...
            if
              is_host_up $h
            then
              exit 1
            else
              exit 0
            fi
          else
            # well... Let's call it successful, after all this is only for testing...
            exit 0
          fi
	done
	exit 1
	;;
status)
	if
	  [ -z "$hostlist" ]
	then
	  exit 1
	fi
	for h in $hostlist
	do
	  if
            ping -w1 -c1 "$h" 2>&1 | grep "unknown host"
          then
	    exit 1
	  fi
	done
	exit 0
	;;
getconfignames)
	echo "hostlist"
	exit 0
	;;
getinfo-devid)
	echo "ssh STONITH device"
	exit 0
	;;
getinfo-devname)
	echo "ssh STONITH external device"
	exit 0
	;;
getinfo-devdescr)
	echo "ssh-based host reset"
	echo "Fine for testing, but not suitable for production!"
	echo "Only reboot action supported, no poweroff, and, surprisingly enough, no poweron."
	exit 0
	;;
getinfo-devurl)
	echo "http://openssh.org"
	exit 0
	;;
getinfo-xml)
	cat << SSHXML
<parameters>
<parameter name="hostlist" unique="1" required="1">
<content type="string" />
<shortdesc lang="en">
Hostlist
</shortdesc>
<longdesc lang="en">
The list of hosts that the STONITH device controls
</longdesc>
</parameter>

<parameter name="livedangerously" unique="0" required="0">
<content type="enum" />
<shortdesc lang="en">
Live Dangerously!!
</shortdesc>
<longdesc lang="en">
Set to "yes" if you want to risk your system's integrity.
Of course, since this plugin isn't for production, using it
in production at all is a bad idea.  On the other hand,
setting this parameter to yes makes it an even worse idea.
Viva la Vida Loca!
</longdesc>
</parameter>

</parameters>
SSHXML
	exit 0
	;;
*)
	exit 1
	;;
esac
