#!/usr/bin/env python

# Software License Agreement (BSD License)
#
# Copyright (c) 2009, Eucalyptus Systems, Inc.
# All rights reserved.
#
# Redistribution and use of this software in source and binary forms, with or
# without modification, are permitted provided that the following conditions
# are met:
#
#   Redistributions of source code must retain the above
#   copyright notice, this list of conditions and the
#   following disclaimer.
#
#   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.
#
# Author: Neil Soman neil@eucalyptus.com

import getopt, sys, os
from euca2ools import Euca2ool, AddressValidationError, ProtocolValidationError, Util

usage_string = """
Revoke a rule for a security group.

euca-revoke [-P | --protocol protocol] [-p | --port-range port_range] 
[-t | --icmp-type-code type:code] [-o | --source-group source_group]
[-u | --source-group-user source_group_user] [-s | --source-subnet source_subnet]
[-h, --help] [--version] [--debug] group_name 

REQUIRED PARAMETERS

group_name			Name of the group to add the rule to.

OPTIONAL PARAMETERS

-P, --protocol                  Protocol ("tcp" "udp" or "icmp").

-p, --port-range		Range of ports for the rule (specified as "from-to").

-t, --icmp-type-code		ICMP type and code specified as "type:code"	

-o, --source-group		Group from which traffic is authorized by the rule.

-u, --source-group-user		User ID for the source group.

-s, --source-subnet		The source subnet for the rule.

"""

version_string = """    euca-revoke version: 1.0 (BSD)"""

def usage():
    print usage_string
    Util().usage(compat=True)

def version():
    print version_string
    sys.exit()

def main():
    euca = None
    try:
        euca = Euca2ool('P:p:o:u:s:t:',
                                   ['protocol=', 'port-range=', 'source-group=',
				    'source-group-user=', 'source-subnet=', 'icmp-type-code='], compat=True)
    except Exception, e:
	print e
        usage()
 
    group_name = None
    protocol = 'tcp' 
    from_port = None
    to_port = None
    source_group_name = None
    source_group_owner_id = None
    cidr_ip = None

    for name, value in euca.opts:
	if name in ('-P', '--protocol'):
	    protocol = value
	elif name in ('-p', '--port-range'):
	    ports = value.split('-')
	    if (len(ports) > 1):
		from_port = int(ports[0])
		to_port = int(ports[1])
	    else:
		from_port = to_port = int(ports[0])
	elif name in ('-o', '--source-group'):
	    source_group_name = value
	    protocol = None
	elif name in ('-u', '--source-group-user'):
	    source_group_owner_id = value  
	elif name in ('-s', '--source-subnet'):
	    cidr_ip = value
        elif name in ('-t', '--icmp-type-code'):
            code_parts = value.split(":")
            if (len(code_parts) > 1):
		try:
                    from_port = int(code_parts[0])
                    to_port = int(code_parts[1])
                except ValueError:
                    print "port must be an integer."
		    sys.exit(1)
        elif name in ('-h', '--help'):
            usage()
	elif name == '--version':
	    version()

    if source_group_name:
        from_port = None
        to_port = None
        protocol = None
 
    for arg in euca.args:
	group_name = arg
	break

    if group_name:
    	if cidr_ip:
	    try:
                euca.validate_address(cidr_ip)
	    except AddressValidationError:
	        print 'Invalid address', cidr_ip
	        sys.exit(1)
	if protocol:
	    try:
	        euca.validate_protocol(protocol)
	    except ProtocolValidationError:
	        print 'Invalid protocol', protocol
	        sys.exit(1)

        euca_conn = euca.make_connection()
	try:
            return_code = euca_conn.revoke_security_group(group_name = group_name,
							src_security_group_name = source_group_name,
							src_security_group_owner_id = source_group_owner_id,
							ip_protocol = protocol,
							from_port = from_port,
							to_port = to_port,
							cidr_ip = cidr_ip)
        except Exception, ex:
            euca.display_error_and_exit('%s' % ex)

        if return_code:
	    print 'GROUP\t%s' % (group_name)
	    permission_string = 'PERMISSION\t%s\tALLOWS' % group_name
	    if protocol:
		permission_string += '\t%s' % protocol 
	    if from_port:
		permission_string += '\t%s' % from_port
	    if to_port:
		permission_string += '\t%s' % to_port
	    if source_group_owner_id:
		permission_string += '\tUSER\t%s' % source_group_owner_id
	    if source_group_name:
		permission_string += '\tGRPNAME\t%s' % source_group_name
	    if cidr_ip:
		permission_string += '\tFROM\tCIDR\t%s' % cidr_ip
	    print permission_string

    else:
	print 'group_name must be specified'
	usage()

if __name__ == "__main__":
    main()
 
