#!/usr/bin/python
"""
###############################################################
Digital Loggers Web Power Switch management
###############################################################
 Description: This is both a module and a script

              The module provides a python class named
              PowerSwitch that allows managing the web power
              switch from python programs.

              When run as a script this acts as a command
              line utility to manage the DLI Power switch.

              This module has been tested against the following 
              Digital Loggers Power network power switches:
                WebPowerSwitch II
                WebPowerSwitch III
                WebPowerSwitch IV
                WebPowerSwitch V
                Ethernet Power Controller III
              
 Author: Dwight Hubbard d@dhub.me
"""
"""
Copyright (c) 2009,2010,2011, 2012, 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 built in modules
import os
import sys
import time
import optparse
from dlipower import *

def _block_to_list(block):
  """ Convert a range block into a numeric list 
      input "1-3,17,19-20"
      output=[1,2,3,17,19,20]
  """
  block+=','
  result=[]
  val=''
  in_range=False
  for letter in block:
    if letter in [',','-']:
      if in_range:
        val2=val
        val2_len=len(val2)
        #result+=range(int(val1),int(val2)+1)
        for value in range(int(val1),int(val2)+1):
          result.append(str(value).zfill(val2_len))
        val=''
        val1=None
        in_range=False
      else:
        val1=val
        val1_len=len(val1)
        val=''
      if letter == ',':
        if val1 != None:
          result.append(val1.zfill(val1_len))
      else:
        in_range=True
    else:
      val+=letter
  return result

if __name__ == "__main__":
    usage = "usage: %prog [options] [status|on|off|cycle|get_outlet_name|set_outlet_name] [range|arg]"
    parser = optparse.OptionParser(usage=usage)
    parser.add_option('--hostname',dest='hostname',default=None,help="hostname/ip of the power switch (default %default)")
    parser.add_option('--timeout',dest='timeout',default=None,help="Timeout for value for power switch communication (default %default)")
    parser.add_option('--cycletime',dest='cycletime',default=None,type=int,help="Delay betwween off/on states for power cycle operations (default %default)")
    parser.add_option('--user',    dest='user',    default=None        ,help="userid to connect with (default %default)"         )
    parser.add_option('--password',dest='password',default=None         ,help="password (default %default)"                       )
    parser.add_option('--save_settings',dest='save_settings',default=False,action='store_true',help='Save the settings to the configuration file')
    parser.add_option("--quiet",dest="quiet",default=False,action="store_true",help="Be quiet, don't print error messages only return error return codes (default False)")
    (options, args) = parser.parse_args()

    switch=PowerSwitch(userid=options.user,password=options.password,hostname=options.hostname,timeout=options.timeout,cycletime=options.cycletime)
    if options.save_settings:
        switch.save_configuration()
    if len(args):
        operation=args[0].lower()
        range=_block_to_list(','.join(args[1:]))
        if len(args) > 1:
            if operation in ['status']:
                print(','.join(switch.command_on_outlets('status',range)))
            elif operation in ['on','poweron']:
                rc=switch.command_on_outlets('on',range)
                if rc and not options.quiet:
                  print >> sys.stderr,"Power on operation failed"
                sys.exit(rc)                
            elif operation in ['off','poweroff']:
                rc=switch.command_on_outlets('off',range)
                if rc and not options.quiet:
                  print >> sys.stderr,"Power off operation failed"
            elif operation in ['cycle']:
                sys.exit(switch.command_on_outlets('cycle',range))
            elif operation in ['get_name','getname','get_outlet_name','getoutletname']:
                print(','.join(switch.command_on_outlets('get_outlet_name',range)))
            elif operation in ['set_name','setname','set_outlet_name','setoutletname']:
                sys.exit(switch.set_outlet_name(args[1],args[2]))
            else:
                print("Unknown argument %s" % args[0])
    else:
        switch.printstatus()