#!/bin/bash
#

# Copyright (C) 2011 Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
# IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
# TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

SSH_USER='root'
SSH_FLAGS='-q -oStrictHostKeyChecking=no'

EXIT_SUCCESS=0
EXIT_FAILURE=1
EXIT_UNKNOWN=2

_run_ssh() {
  local host="$1"
  local command="$2"

  ssh $SSH_FLAGS "$SSH_USER@$host" "$command" 1>&2
  return $?
}

_power_on() {
  echo 'power-on not supported in this script' >&2
  exit $EXIT_FAILURE
}

_power_off() {
  local host="$1"

  if ! _run_ssh "$host" 'shutdown -h now'; then
    echo "Failure during ssh to $host" >&2
    exit $EXIT_FAILURE
  fi
}

_power_cycle() {
  local host="$1"

  if ! _run_ssh "$host" 'shutdown -r now'; then
    echo "Failure during ssh to $host" >&2
    exit $EXIT_FAILURE
  fi
}

_power_status() {
  local host="$1"

  if fping -q "$host" > /dev/null 2>&1; then
    echo '{ "powered": true }'
  else
    echo '{ "powered": false }'
  fi
}

_health() {
  echo 'health not supported in this script' >&2
  exit $EXIT_FAILURE
}

_action() {
  local command="$1"
  local host="$2"

  case "$command" in
    power-on)
      _power_on "$host"
      ;;
    power-off)
      _power_off "$host"
      ;;
    power-cycle)
      _power_cycle "$host"
      ;;
    power-status)
      _power_status "$host"
      ;;
    health)
      _health "$host"
      ;;
    *)
      echo "Unsupported command '$command'" >&2
      exit $EXIT_FAILURE
      ;;
  esac
}

main() {
  if [[ $# != 2 ]]; then
    echo "Wrong argument count, got $#, expected 2" >&2
    exit $EXIT_FAILURE
  fi

  _action "$@"

  exit $EXIT_SUCCESS
}

main "$@"
