#!/opt/vmware/bin/python

#######################################################################
# Copyright (C) 2012-2013 VMware, Inc.  All Rights Reserved.
#######################################################################

#
# Command line interface to the IPResolver module(defined in hostname.py)
# that is to compute a name or an address which can be
# used by services running on any machine to connect back to us. This is not
# necessarily the system hostname (which may be bogus). Instead, it is based
# on picking an externally-resolvable IP address, and then _if_ it has a sane
# DNS listing (i.e. both forward and reverse lookups consistent), then we pick
# that name, else we choose the address.  This is the value to use in URLs
# that are registered with CIS, and also for Lotus instances to announce
# themselves to each other.
#
# Usage:
#    syshostname [-v|-q] [-l] [-s [pnid]]
#
# When invoked with -s (--set), the script will either accept an explicit pnid
# (preferred network id) passed in as an explicit argument, or if it isn't,
# it will use a computed value to set install-parameters.  The script sets
# the following install-parameters:
#
#    system.hostname = the selected PNID
#    system.hostname.type = fqdn|ipv4|ipv6
#    system.urlhostname = a form of the PNID suitable for use in URLs.
#
# (this distinction is important for IPv6 addresses, which have to be
# enclosed in [] in URLs.)
#

'''
Compute the externally-resolvable hostname or address for service registration
'''

import os
import optparse
import sys

sys.path.append(os.environ['VMWARE_PYTHON_PATH'])

from appliance.hostname import IPResolver, setPreferredNetworkId
from cis.utils import setupLogging
from cis.defaults import get_cis_log_dir

if __name__ == "__main__":
    logDir = os.path.join(get_cis_log_dir(), 'cloudvm')
    setupLogging("syshostname", logMechanism='file', logDir=logDir)

    parser = optparse.OptionParser()
    parser.add_option("-s", "--set", action="store_true", dest="setAddress",
                      help="Set the install-parameter system.hostname")
    parser.add_option("-v", "--verbose", action="store_true", dest="verbose",
                      default=False, help="Be verbose")
    parser.add_option("-q", "--quiet", action="store_false", dest="verbose",
                      help="Be quiet")
    parser.add_option("-l", "--list", action="store_true", dest="listAddresses",
                      help="List discovered IP addresses and FQDNs")
    (options, args) = parser.parse_args()

    pnid = None
    if len(args) > 0:
        if not options.setAddress:
            raise ValueError("pnid specified without -s option")
        pnid = args[0]

    # XXX: Do we really need syshostname? What is it doing in addition to
    # pnid-manager? Can we in visl-support-integration directly use IPResolver
    # rather than calling exec to syshostname.
    resolver = IPResolver.getIPResolver()
    if (pnid is not None and not resolver.isValidNetworkID(pnid)):
        raise ValueError("pnid %s specified is not valid" % pnid)

    if pnid is None:
        pnid = resolver.preferredNetworkId()
        if pnid is None:
            raise ValueError("Unable to infer pnid.")

    if options.listAddresses:
        resolver.dump()

    if options.setAddress:
        if options.verbose:
            print "Setting system.hostname to %s" % pnid
        setPreferredNetworkId(pnid)
    else:
        print pnid
