#!/usr/bin/env python
#
# Copyright C 2002-2012 by Isilon Systems LLC. All rights not expressly
# granted herein are reserved.
# Created in the United States of America.
#
# This digital media is protected by U.S. and international copyright and
# intellectual property laws. Unless otherwise specified, all information
# and screens appearing as part of this digital medium, including
# software, services, documents, text, images, icons, and logos design;
# the selection, assembly, arrangement, and design thereof; and the code
# that enables its presentation, are the sole property of Isilon Systems,
# Inc.
#
# Except as otherwise required by applicable law, no part of any
# copyrighted material may be reproduced, modified, translated,
# distributed, published, or transmitted by any means, electronic or
# mechanical, for any purpose, without the prior written consent of Isilon
# Systems.
#
# Isilon and Isilon Systems are registered trademarks of Isilon Systems,
# Inc.  Legion is a trademark of Isilon Systems, Inc.  All other
# trademarks and registered trademarks are the property of their
# respective holders.
#
# $Id:$

"""
The implementation of the support only 'isi_sc_put_ip' command.
"""

from copy import copy
from optparse import OptionParser, Option
import string
import re
import sys

import isi.net.flexnet as flx
import isi.app.lib.cluster as cluster
Cluster = cluster.Cluster()

#
# Helpers and validators
#

class ArgumentError(Exception):
    """
    Raised when an ArgumentType fails to parse the argument properly.
    """
    def __init__(self, msg):
        self.msg = msg

    def __str__(self):
        return self.msg

def validate_iface(option, opt, value):
    def filterIfacesByNode(x):
        if int(x.id.devid) == int(node):
            return True
        return False

    # validation in 2 steps:
    #   1: make sure it follows format (regex)
    #   2: make sure it exists by finding it in the config
    matches = re.search("[0-9]+\:[a-zA-Z0-9]+(-agg)?\-[0-9]+", value)
    if matches is None:
        raise ArgumentError("%s is not a valid format for an iface" % value)

    components = string.split(value, ':')
    lnn = int(components[0])
    try:
        lnnmap = Cluster.lnn_to_id_map()
        node = lnnmap.get(lnn)
        if node is None:
            raise ArgumentError("LNN %d doesn't exist" % lnn)
    except IndexError:
        raise ArgumentError("Could not find node %d" % lnn)

    lni = components[1]

    # now lets find the lni on the node
    config = load_flx_config()
    interfaces = filter(filterIfacesByNode, config.ifaces)
    config.close()

    if len(interfaces) == 0:
        raise ArgumentError("Could not find node %s in Flexnet" % node)

    for iface in interfaces:
        if iface.id.lni_name == lni:
            return iface.id

    raise ArgumentError("Could not find interface %s" % value)

class Iface(Option):
    TYPES = Option.TYPES + ("Iface",)
    TYPE_CHECKER = copy(Option.TYPE_CHECKER)
    TYPE_CHECKER["Iface"] = validate_iface

def validate_ip(option, opt, value):
    try:
        if len(value) == 0:
            return flx.Addr(0L)
        else:
            return flx.Addr(value)
    except flx.AddrError, e:
        raise ArgumentError(str(e))

class IP(Option):
    TYPES = Option.TYPES + ("IP",)
    TYPE_CHECKER = copy(Option.TYPE_CHECKER)
    TYPE_CHECKER["IP"] = validate_ip


#
# Actually apply the change
#

def load_flx_config():
    config = flx.config_try_load()
    return config

def sc_put_ip(options):
    config = load_flx_config()

    ip = options.sc_ip
    iface = options.sc_iface
    lnn = Cluster.id_to_lnn_map().get(iface.devid)

    print("Putting %s on %s:%s" % (ip, lnn, iface.lni_name))
    flx.sc_put_ip(ip, iface)

    config.close()

if __name__ == '__main__':
    try:
        usage = "usage: %prog --sc-ip <ip> --sc-iface <iface>"
        options = [
            IP("--sc-ip", type="IP",
                help="IP address to move/put (must be in a dynamic IP Pool)"),
            Iface("--sc-iface", type="Iface",
                help="Destination node:interface for IP (must be a member of "
                    "the same dynamic IP Pool as the IP being moved)")
        ]
        parser = OptionParser(usage=usage, option_list=options)

        (options, args) = parser.parse_args()

        if not options.sc_ip:
            parser.error("Missing argument: --sc-ip")
        if not options.sc_iface:
            parser.error("Missing argument: --sc-iface")
        sc_put_ip(options)
    except Exception as e:
        print "isi_sc_put_ip failed: %s" % str(e)
        sys.exit(1)
