#  ========= CONFIDENTIAL =========
#
#  Copyright (C) 2010-2014 Dell, Inc. - ALL RIGHTS RESERVED
#
#  ======================================================================
#   NOTICE: All information contained herein is, and remains the property
#   of Dell, Inc. The intellectual and technical concepts contained herein
#   are proprietary to Dell, Inc. and may be covered by U.S. and Foreign
#   Patents, patents in process, and are protected by trade secret or
#   copyright law. Dissemination of this information or reproduction of
#   this material is strictly forbidden unless prior written permission
#   is obtained from Dell, Inc.
#  ======================================================================
import logging
import re
from dcm.agent import exceptions, utils

import dcm.agent.jobs.direct_pass as direct_pass


_g_logger = logging.getLogger(__name__)


def _is_valid_hostname(hostname):
    if len(hostname) > 255:
        return False
    if hostname[-1] == ".":
        hostname = hostname[:-1]
    allowed = re.compile("(?!-)[A-Z\d-]{1,63}(?<!-)$", re.IGNORECASE)
    return all(allowed.match(x) for x in hostname.split("."))


def legalize(hostname):
    new_hostname = []
    for c in hostname:
        if (c >= 'a' and c <= 'z') or\
            (c >= 'A' and c <= 'Z') or\
            (c >= '0' and c <= '9') or\
                c == '-' or c == '.':
            new_hostname.append(c)
        elif c == ' ' or c == '_':
            new_hostname.append('-')
    if len(new_hostname) < 1:
        return 'unknown'

    return ''.join(new_hostname)


class Rename(direct_pass.DirectPass):

    protocol_arguments = {
        "serverName":
        ("The host name to which this server will be set.",
         True, str, None)
    }

    def __init__(self, conf, job_id, items_map, name, arguments):
        super(Rename, self).__init__(
            conf, job_id, items_map, name, arguments)

        hname = legalize(arguments["serverName"])
        if not _is_valid_hostname(hname):
            raise exceptions.AgentPluginMessageException(
                "%s is an invalid hostname" % hname)

        self.ordered_param_list = [hname]

    def run(self):
        private_ips = self.conf.meta_data_object.get_ipv4_addresses(self.conf)
        if not private_ips:
            reply_doc = {
                "return_code": 1,
                "message": "No IP Address was found"
            }
            return reply_doc

        utils.log_to_dcm(logging.DEBUG, "Acquired ip addr %s" % private_ips[0])
        self.ordered_param_list.append(private_ips[0])

        return super(Rename, self).run()


def load_plugin(conf, job_id, items_map, name, arguments):
    return Rename(conf, job_id, items_map, name, arguments)

@@ -876,698 +876,308 @@
 def 
-_
 is_
-valid_hostname(hostname):%0A    if len(hostname) %3E 255:%0A        return False%0A    if hostname%5B-1%5D == %22.%22:%0A        hostname = hostname%5B:-1%5D%0A    allowed = re.compile(%22(?!-)%5BA-Z%5Cd-%5D%7B1,63%7D(?%3C!-)$%22, re.IGNORECASE)%0A    return all(allowed.match(x) for x in hostname.split(%22.%22))%0A%0A%0Adef legalize(hostname):%0A    new_hostname = %5B%5D%0A    for c in hostname:%0A        if (c %3E= 'a' and c %3C= 'z') or%5C%0A            (c %3E= 'A' and c %3C= 'Z') or%5C%0A            (c %3E= '0' and c %3C= '9') or%5C%0A                c == '-' or c == '.':%0A            new_hostname.append(c)%0A        elif c == ' ' or c == '_':%0A            new_hostname.append('-')%0A    if len(new_hostname) %3C 1:%0A        return 'unknown'%0A%0A    return ''.join(new_host
+legal(proposed_name):%0A    regex = %22%5E((%5Ba-zA-Z%5D%7C%5Ba-zA-Z%5D%5Ba-zA-Z0-9%5C-%5D*%5Ba-zA-Z0-9%5D)%5C.)*(%5BA-Za-z%5D%7C%5BA-Za-z%5D%5BA-Za-z0-9%5C-%5D*%5BA-Za-z0-9%5D)$%22%0A    allowed = re.compile(regex)%0A    if allowed is None:%0A        raise exceptions.AgentPluginMessageException(%0A                %22%25s is an invalid hostname%22 %25 proposed_
 name
@@ -1532,24 +1532,16 @@
     
-hname = 
+is_
 legal
-ize
 (arg
@@ -1566,162 +1566,8 @@
 %22%5D)%0A
-        if not _is_valid_hostname(hname):%0A            raise exceptions.AgentPluginMessageException(%0A                %22%25s is an invalid hostname%22 %25 hname)%0A%0A
     
@@ -1601,13 +1601,31 @@
  = %5B
-hn
+arguments%5B%22serverN
 ame
+%22%5D
 %5D%0A%0A 

Throw an error early when the server name is not known.