#!/usr/bin/python
#
# Copyright (c) 2015 The New Mexico Consortium
# 
# {{{NMC-LICENSE
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
# THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
# DAMAGE.
#
# }}}
#
# Add a log entry
#

import os,sys,getopt,pprint

from nmc.couchdb import CouchDB
from nmc.log import Log
from nmc.nanek import Blade, Slot, Chassis, LogEntry
from nmc.bladeutilsconfig import BladeUtilsConfig

def main():
    """
    Program entry point
    """
    options = readOptions()

    config = BladeUtilsConfig()

    # Couch database connector
    couch = CouchDB.withConfigFile()

    params = {}

    bladeDocId     = options.get('blade', None)
    chassisDocId   = options.get('chassis', None)
    slotDocId      = options.get('slot', None)
    memoryReplaced = options.get('memoryReplaced', None)

    if chassisDocId:
        params['chassisDocId'] = chassisDocId

    if slotDocId:
        params['slotDocId'] = slotDocId

    if not bladeDocId and slotDocId:
        tuple = Slot.toBlade(couch, params['slotDocId'])

        if tuple and len(tuple) > 0 and len(tuple[0]) == 2:
            params['bladeDocId'] = tuple[0][1]

    if memoryReplaced:
        params['message'] = 'Replaced memory %s' % memoryReplaced
        params['severity'] = 'FIX'

    params['timestamp'] = CouchDB.now()

    log = LogEntry(params)
    log.persist(couch)

    Log.debug(10, params)

def readOptions():
    progName = sys.argv[0]
    config = BladeUtilsConfig()

    optlist = None
    args = None

    options = {}

    try:
        optlist, args = getopt.getopt(sys.argv[1:], 'n:d:h', ['debug=', 'help', 'chassis=', 'slot=', 'blade=', 'memory-replaced='])

    except getopt.GetoptError as err:
        print(err)
        usage(progName)
        sys.exit(0)

    num=None

    # Process the options
    for (opt,value) in optlist:
        if opt == '--help' or opt == '-h':
            usage(progName)
            sys.exit(0)

        if opt == '--debug' or opt == '-d':
            Log.debugLevel = int(value)

        if opt == '--chassis':
            options['chassis'] = int(value)

        if opt == '--slot':
            options['slot'] = int(value)

        if opt == '--blade':
            options['blade'] = value

        if opt == '--memory-replaced':
            options['memoryReplaced'] = value

    # Handle slot option BEFORE the chassis option
    if options.has_key('slot'):
        if not options.has_key('chassis'):
            print ('--slot option requires --ch option\n')
            usage(progName)
            sys.exit(1)
        else:
            slotDocId = config.options['chassis']['slot_docid_format'] % (options['chassis'] , options['slot'])
            options['slot'] = slotDocId
            Log.debug(100, slotDocId)

    # Handle chassis option after slot option
    if options.has_key('chassis'):
        chassisDocId = config.options['chassis']['chassis_docid_format'] % options['chassis']
        options['chassis'] = chassisDocId
        Log.debug(100, chassisDocId)

    return options

def usage(progName):
    print 'Usage: %s [--debug=N|-d N]' % progName

# Program entry point
if __name__ == "__main__":
    main()
