#!/usr/bin/env python

# Copyright C 2002-2008 by Isilon Systems, Inc. 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.


import getopt
import isi.sys.version as version
import sys
import cPickle
import pprint
import syslog
import traceback
import os

try:
    def usage(exitno):
        print """Usage %s [OPTIONS] 
Options:
  -h                 Show Usage  
  --shim=SHIM        Use SHIM as the Shim Context File, '-' for stdin
  -p | --pretty      Output in prett-print format
""" % sys.argv[0]
        os._exit(exitno)

    path = None
    pretty = False

    try:
        opts, args = getopt.getopt(sys.argv[1:], 'hp', ['shim=', 'pretty'])
        for o, a in opts:
            if o == "-p" or o == '--pretty':
                pretty = True
            if o == '--shim':
                path = a
            if o == '-h':
                usage(0)
    except getopt.GetoptError:
        usage(1)

    if path:
        try:
            if path == "-":
                shimfile = sys.stdin
            else:
                shimfile = open(path, 'r')
            shim = shimfile.read()
            shimfile.close()
        except IOError, (errnumber, errorstring):
            syslog.syslog(syslog.LOG_ERR | syslog.LOG_USER, "IOError %d, " +
                    "could not open %s: %s" % (errnumber, path, errorstring))
            os._exit(1)
    else:
        shim = None

    nodegatherer= version.Gatherer(shim)
    versiondict = nodegatherer.gather()

    if pretty:
        pprint.pprint(versiondict)
    else:
        cPickle.dump(versiondict, sys.stdout, 0)
except:
    syslog.syslog(syslog.LOG_ERR | syslog.LOG_USER, "isi_gather_node_info " +
            "failed \n" + reduce(lambda x, y: x + y, 
            traceback.format_exception(sys.exc_info()[0], sys.exc_info()[1], 
            sys.exc_info()[2])))
    os._exit(1)
