#!/usr/bin/env python

# Previous, dongle-only code would call:
#   devices.dongle_sync() ==> renamed to devices.dongle_sync_no_eeprom
# which calls devices.dongle.slice.sync()
# which calls, for each line in dongle_sync_files, in turn:
#   devices.dongle.slice.pull_file() <-- dongle
#   devices.dongle.slice.push_file() --> dongle
#
# New, dongle- OR eeprom- OR both- code (in hw.dongle):
# 1.   Pull from nonvolatile: (dongle has greater priority)
# 1.1    Pull from VPD(EEPROM) to local
# 1.2    Pull from dongle      to local
# 2.   Push results to nonvolatile:
# 2.1    Push to VPD(EEPROM) from local
# 2.2    Push to dongle      from local
#
# Note the pull order (first EEPROM, then dongle) is chosen to
# enforce the priority: If both EEPROM and dongle are present,
# the dongle has precedence, and therefore is pulled last
# (overwriting both prior local file, and EEPROM, data).
# The ordering of step 2, push, should not matter.
# All of this can be condensed to two local function calls:
# pull(), push().
# A notable difference from earlier code: *ALL* files will be pushed
# or pulled, at EACH step, as opposed to earlier imdd.devices.sync()
# code, which would pull/push each individual file in turn.

import getopt
import logging
import os
import syslog
import sys

import isi.hw.dongle as hwdongle
import isi.hw.imdd.log as imddlog

log = None

def help():
    print "isi_dongle_sync [-p | -d | -f | -i | -h]"
    print "\t-p push to dongle"
    print "\t-d display dongle information"
    print "\t-f force push to dongle (rm nonexistent files)"
    print "\t-i install dongle fs"
    print "\t-h this messages"
    print "\tdefault: sync with dongle"

def push(force_rmv=False):
    return hwdongle.dongle_push(force_rmv)

def install():
    return hwdongle.dongle_fix(force=True)

def log_setup():
    global log
    syslog.openlog('isi_dongle_sync', 0, syslog.LOG_USER)
    # Required logger setup for hw.dongle reporting.
    log = hwdongle.dongle_sync_logger()

def log_line(line):
    global log
    # Using the logging module would be preferable here, but the
    # SysLogHandler is not working at the moment. See bug 32533.
    print line
    syslog.syslog(syslog.LOG_NOTICE, line)
    # Using the (hw.dongle based) logger as well
    log.info(line)

def log_error(line):
    global log
    print line
    syslog.syslog(syslog.LOG_ERR, line)
    # Using the (hw.dongle based) logger as well
    log.error(line)

def display():
    dongle_info = hwdongle.dongle_info()
    line = "Dongle serial number: "
    if (dongle_info == None or 'serialno' not in dongle_info):
        line += "Unknown"
    else:
        line += dongle_info['serialno']

    log_line(line)
        
    line = "Dongle system configuration: "
    if (dongle_info == None or 'sysconfig' not in dongle_info):
        line += "Unknown"
    else:
        line += dongle_info['sysconfig']

    log_line(line)
    return 0

def sync():
    return hwdongle.dongle_sync()

def load():
    result = 0
    errors = hwdongle.dongle_user_init("/dev/ad0")
    if errors:
        result = 1
        for error in errors:
            log_error(error)
    return result

def main():
    global log
    result = 0

    opts, pargs = getopt.getopt(sys.argv[1:], 'pfihd')
    if (len(opts) > 1 or (len(opts) == 1 and opts[0][0] == '-h')):
        help()
        return 1

    log_setup()
    imddlog.log_console()

    result = load()
    if result != 0:
        # Don't attempt any dongle(eeprom) syncing if errors
        return result

    if (len(opts) == 1):
        if (opts[0][0] == '-f'):
            result = push(force_rmv=True)
        elif (opts[0][0] == '-d'):
            result = display()
        elif (opts[0][0] == '-p'):
            result = push()
        elif (opts[0][0] == '-i'):
            result = install()
        # Else ???
    else:
        result = sync()

    if result:
        log_error('Errors encountered during isi_dongle_sync')

    return result

sys.exit(main())

