#!/usr/bin/python
# Copyright (C) 2006-2007 XenSource Ltd.
# Copyright (C) 2008-2009 Citrix Ltd.
#
# This program is free software; you can redistribute it and/or modify 
# it under the terms of the GNU Lesser General Public License as published 
# by the Free Software Foundation; version 2.1 only.
#
import sys
sys.path.insert(0, "/opt/xensource/sm")
sys.path.insert(0, "/opt/xensource/sm/snapwatchd")
import util
import xslib
import random
import os
from StorageHandlerUtil import XenCertPrint

NO_OF_PATHS_PER_PORT = 2

def help():
    print "Usage: blockunblockhbapaths <block/unblock> <noOfPaths> switch-ip:username:password:port1,port2..."
    sys.exit(-1)
    
def blockUnblockPort(blockOrUnblock, ip, username, password, port):
    try:
        XenCertPrint("In blockUnblockPort with options: %s, %s, %s, %s" % (ip, username, password, port))
	if blockOrUnblock:
	    cmd = [os.path.join(os.getcwd(),'blockunblockHBAPort.sh'), ip, username, password, port, 'portdisable']
	else:
	    cmd = [os.path.join(os.getcwd(),'blockunblockHBAPort.sh'), ip, username, password, port, 'portenable']
	    
	XenCertPrint("calling %s" % cmd)
        util.doexec(cmd, '')
    except Exception, e:
        util.SMlog("There was an exception in blocking port: %s" % port)
	
# Test Cmdline args
if len(sys.argv) != 4:
    help()
    
# Now extract all parameters from the command line
op = sys.argv[1]
ip = sys.argv[3].split(':')[0]
username = sys.argv[3].split(':')[1]
password = sys.argv[3].split(':')[2]
portList = sys.argv[3].split(':')[3].split(',')
noOfPortsToBlock = 0

if op == 'block':    
    noOfPortsToBlock = random.randint(1,len(portList) - 1)
    XenCertPrint("No of ports to block: %s" % str(noOfPortsToBlock))
    portList = random.sample(portList, int(noOfPortsToBlock))
    retVal=ip + ':' + username + ':' + password + ':'
else:
    retVal = ''
    
for port in portList:
    if op == 'block':
        blockUnblockPort(True, ip, username, password, port)
	retVal += port
	retVal += ','
        XenCertPrint(port)
	XenCertPrint(retVal)
    elif op == 'unblock':
	blockUnblockPort(False, ip, username, password, port)

retVal = retVal.strip(',')
retVal += '::'
retVal += str(noOfPortsToBlock * NO_OF_PATHS_PER_PORT)
xs_handle = xslib.xs_daemon_open()
xslib.setval(xs_handle, '/xencert/block-unblock-over', '1')
xslib.xs_daemon_close(xs_handle)
if op == 'block':
    sys.stdout.write(retVal)
sys.exit(0)
