#!/usr/bin/env python

# Copyright 2011 by Isilon Systems LLC. 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.
#
# $Id$

import getopt
import logging
import os
import sys
import time

import isi.hw.hal as hal
import isi.hw.i2c as i2c
import isi.hw.version as hwver
import isi.ui.lcd.config as config
import isi.ui.lcd.noritake as nori

## Setup logging
log = logging.getLogger('lcd.init')

## literals
ISILON_V1_I2C_ADDR  = 0x46

def lcd_initialize():
    # Don't buffer stdout/stderr 
    sys.stdout = os.fdopen(sys.__stdout__.fileno(), 'w', 0)
    sys.stderr = os.fdopen(sys.__stderr__.fileno(), 'w', 0)

    os.system("/usr/bin/isi_hwtools/isi_fputil -r")

    # sleep to allow time for USB discovery
    time.sleep(2.0)

    # Open the LCD
    try:
        lcd = nori.Display()
        lcd.open(config.LCDConfig.getDeviceFile())
        lcd.verifyModel()

        lcd.close()
    except Exception, e:
        print >> sys.stderr, "Failed to initialize LCD: %s" % str(e)
        sys.exit(1)

# XXX FIXME XXX
# For now, this function is only a stub, but at some point, we might want to
# be able to detect a front panel that only has a bootloader (no operational
# firmware) and automatcially flash the firmware.
def flash():
    return 0

def main(argv):
    # Currently this only applies to ISILON_V1 front panels
    if hal.getLcdType() != hwver.LCDVER_ISILON_V1:
        return 0

    # Setup "lcd" logger instance with a stream handler. We run during
    # early boot, so we must log any problems to the console without
    # the timestamp, log level, etc.
    log = logging.getLogger('lcd')
    log.addHandler(logging.StreamHandler(sys.stderr))
    log.setLevel(logging.WARNING)

    # if no front panel is currently present, just exit
    if not hal.hasFrontPanelDisplay():
        print "Isilon Front Panel not present - skipping initialization" 
        return 0

    lcd_initialize()

    return 0

sys.exit(main(sys.argv[1:]))



