#!/usr/bin/env python2.6
# vim: tabstop=4 shiftwidth=4 softtabstop=4

# Copyright (c) 2011 Citrix Systems, Inc.
#
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.

import sys
import pprint
import logging

from geppetto.hapi import config_util
from geppetto.hapi import interface
from geppetto.hapi import exception

logger = logging.getLogger('host-details-get')


if __name__ == "__main__":
    try:
        with open('/tmp/hapi.validated', 'r') as f:
            state = f.read()
            if state != 'SET':
                logger.error('Invalid credentials, bailing!')
                sys.exit(4)
    except IOError as e:
        logger.error('Cannot determine if credentials are valid, bailing!')
        sys.exit(5)

    if(len(sys.argv) == 2) and sys.argv[1] == 'virt-type':
        print config_util.get_running_hypervisor_type()
        sys.exit(0)
    elif(len(sys.argv) == 2) and sys.argv[1] == 'default-vlan-if':
        print config_util.get_hypervisor_default_vlan_interface()
        sys.exit(0)

    try:
        session = interface.Session.createSession()
        session.login()

        if len(sys.argv) == 2:
            host_info = session.Host.get_properties([sys.argv[1]])
            print host_info[sys.argv[1]]
        elif len(sys.argv) == 3:
            host_info = session.Host.get_properties([sys.argv[1]])
            print host_info[sys.argv[1]][sys.argv[2]]
        else:
            host_info = session.Host.get_properties()
            pprint.pprint(host_info)
    except exception.HAPIFailure, e:
        logger.error('Failure: exit_code(%s), message(%s)' \
                                            % (e.code, e.message))
        if e.inner:
            logger.error('Inner failure -->')
            logger.exception(e.inner)
        sys.exit(1)
    except KeyError, e:
        logger.error('Property not found')
        logger.exception(e)
        sys.exit(2)
