#!/usr/bin/python
""" 
Stonith Agent for Digital Loggers Network Power Switches
for Linux HA Clusters 

This agent has been tested against the following Digital Loggers Power 
network power switches:
  WebPowerSwitch II
  WebPowerSwitch III
  WebPowerSwitch IV
  WebPowerSwitch V
  Ethernet Power Controller III

It may work for other models of Digital Loggers power switches as well
"""

"""
Copyright (c) 2009, Dwight Hubbard
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 OWNER 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.
"""

# Python Standard Library Imports
import sys

# 3rd Party python Modules
# dlipower - http://pypi.python.org/pypi/dlipower/
import dlipower

# This fencing driver uses the dlipower python module to manage the power switch
# the dlipower package installs a dlipower.py script that provides a command line
# interface to manage the switch.
RELEASE_VERSION="0.0.5"

device_opt = [  "help", "version", "agent", 
		"action", "ipaddr", "login", "passwd","port", "nodename",
		"timeout","cycletime"]

if __name__ == "__main__":
    # Parse the input into a dict named options
    options={}
    unknown_options=[]
    for line in sys.stdin.readlines():
        temp=line.strip().split('=')
        if len(temp) == 2:
            key=temp[0].strip()
            value=temp[1].strip()
            if line[0] != '#' and len(key):
                if key in device_opt:
                    options[key]=value
                else:
                    unknown_options.append(key)

        # Print a warning about unknown options that where passed
        if len(unknown_options):
            print >> sys.stderr,'Unknown options, ignoring: ',' '.join(unknown_options)

    # Make sure we got all the needed options to do the action requested
    if not set(['ipaddr','login','passwd','action']).issubset(set(options)):
        print >> sys.stderr,'Did not receive all required options, missing',' '.join(list(set(['ipaddr','login','passwd','action']).difference(set(options))))
        sys.exit(1)
        	
    if 'port' not in options.keys() and options['action'] in ['off','on','reboot','status']:
        print('Cannot execute action, no port specified')
        sys.exit(1)

        # The dlipower powerswitch object uses the default values if options have a value of None
        # so we set these options to the passed value or None if they weren't passed which
        # will cause the dlipower module to use it's internal defaults.
        # The dlipower module will store default settings in the ~/.dlipower.conf file of the
        # user running the command.  For clarity it's a good idea to pass the options when
        # using a cluster.
    if 'cycletime' not in options.keys():
        options['cycletime']=None
        
    if 'timeout' not in options.keys():
        options['timeout']=None
                
    switch=dlipower.powerswitch(hostname=options['ipaddr'],userid=options['login'],password=options['passwd'],timeout=options['timeout'],cycletime=options['cycletime'])
    if options['action'].lower() in ['off']:
        sys.exit(switch.off(int(options['port'])))
    if options['action'].lower() in ['on']:
        sys.exit(switch.on(int(options['port'])))
    if options['action'].lower() in ['reboot']:
        sys.exit(switch.cycle(int(options['port'])))
    if options['action'].lower() in ['status']:
        status=switch.status(int(options['port']))
        if status == 'ON':
            sys.exit(0)
        if status == 'Unknown':
            sys.exit(1)
        if status == 'OFF':
            sys.exit(2)
    if options['action'].lower() in ['list','monitor']:
        sys.exit(switch.printstatus())
