#!/bin/sh
#
# Title: check_3gstore_outlet
# Author: Eric Loyd (eloyd@everwatch.global, eric@bitnetix.com)
# Purpose:
#       Sends a CGI command off to a 3gstore IP controlled power outlet and returns status for outlet X
#       It assumes "on" is OKAY, and anything else is CRITICAL

# "http://outlet.smartvox.net/cgi-bin/control.cgi?target=2&control=2"

hostname=""
username="admin"
password="admin"
outlet=0
command=""
outlet_status=0
debug=""

while [ -n "$1" ]; do
  case "$1" in
    -H) hostname="$2"; shift 2;;
    -c) command="$2"; shift 2;;
    -u) username="$2"; shift 2;;
    -p) password="$2"; shift 2;;
    -o) outlet="$2"; shift 2;;
    -d) debug="true"; shift 1;;
    *) shift 1;;
  esac
done

[ -z "$hostname" ] && echo "UNKNOWN: no hostname specified." && exit 3
[ -z "$username" ] && echo "UNKNOWN: no username specified." && exit 3
[ -z "$password" ] && echo "UNKNOWN: no password specirfid." && exit 3
if [ "$outlet" -ne "1" -a "$outlet" -ne "2" ]; then
  echo "UNKNOWN: Invalid outlet number (${outlet})."
  exit 3
fi

check_outlet_status() {
  [ -n "$debug" ] && echo curl -s --user ${username}:${password} http://${hostname}/xml/outlet_status.xml | grep -oPm1 "(?<=<outlet_status>)[^<]+"
  outlets=`curl -s --user ${username}:${password} http://${hostname}/xml/outlet_status.xml | grep -oPm1 "(?<=<outlet_status>)[^<]+"`
  outlet1=`echo $outlets | awk -F, '{print $1}'`
  outlet2=`echo $outlets | awk -F, '{print $2}'`
  [ "$outlet" = "1" ] && outlet_status="$outlet1"
  [ "$outlet" = "2" ] && outlet_status="$outlet2"
  return $outlet_status
}

# Instead of checking, if command is not blank, then we're changing the state
if [ -z "$command" ]; then
  check_outlet_status $outlet
  case "$?" in
    1) echo "OK: $outlet is powered up"; exit 0;;
    *) echo "CRITICAL: $outlet is not powered up"; exit 2;;
  esac
else
  case "$command" in
    OFF) control=0;;
    ON) control=1;;
    TOGGLE) control=2;;
    RESTART|RESET) control=3;;
    *) control="";;
  esac
  if [ -z "$control" ]; then
    echo "UNKNOWN: Invalid command ($command). Should be ON, OFF, RESET, or TOGGLE."
    exit 3
  fi
  [ -n "$debug" ] && echo curl -s --user ${username}:${password} "http://${hostname}/cgi-bin/control.cgi?target=${outlet}&control=${control}"
                  output=`curl -s --user ${username}:${password} "http://${hostname}/cgi-bin/control.cgi?target=${outlet}&control=${control}"`
  check_outlet_status $outlet
  case "$?" in
    1) echo "OK: $outlet is powered up"; exit 0;;
    *) echo "OK: $outlet is not powered up"; exit 2;;
  esac
fi
