#!   /usr/bin/env   python
#    coding: utf8

# Copyright INCAA Computers, 2012
# Author: Bert Gooijer <bert.gooijer@incaacomputers.com>
# Licence: GPL v2 or later.
# Website: http://www.ohwr.org

from ptsexcept import *
from utilFunctions import *

import sys
import time
import subprocess
import datetime

from spec import *
from ad9516 import *
from adf4002 import *
from dac import *
from sys import __stdout__


from spec_identification import *

sdbfs_image_filename = "fmc-dac600m-sdbfs.bin"
frugenerator = "../software/fmc-bus/tools/fru-generator"
gensdbfs = "../software/fpga-config-space/sdbfs/userspace/gensdbfs"
sdbfs_dir = "sdbfs"


"""
test07: Writes and validates the card's EEPROM.
"""

FIRMWARE_PATH = '/../gateware/syn/spec_top.bin'

def main (card=None, serial = "000", default_directory='.',suite=None, configure_fpga=True):
    

    specid = spec_identification()[0];
    if specid < 0 :
        raise PtsCritical("Bus number of FmcDac600m12b1chadds was not found")

    # init spec
    carrier=spec( FIRMWARE_PATH, specid, configure_fpga );
     
    print "Creating IPMI-FRU information"
    
    cwd=os.path.dirname(os.path.realpath(__file__))
    cwd=cwd+"/"

    fru_gen_path    = cwd+frugenerator
    gensdbfs_path   = cwd+gensdbfs
    sdbfs_path      = cwd+sdbfs_dir


    ipmi_vendor = "CERN"
    ipmi_name = "fmc-dac600m"
    ipmi_part = "EDA-03010-V3-0"

    print "Vendor: %s" % ipmi_vendor
    print "Name: %s" % ipmi_name
    print "Part: %s" % ipmi_part
    print "Serial: %s" % serial 

    subprocess.call(
        [fru_gen_path,
        # vendor
        "-v %s" % ipmi_vendor, 
        # name
        "-n %s" % ipmi_name, 
        # serial
        "-s", serial,
        # part
        "-p %s" % ipmi_part, 
        # output
        "-o", sdbfs_path+"/IPMI-FRU" ]
        )

    print "IPMI-FRU information stored in "+sdbfs_path+"/IPMI-FRU"
    return_value = carrier.write_eeprom_from_file(sdbfs_path+"/IPMI-FRU", 0)

    print "Return value: %d" % return_value
    if (return_value == -1):
        raise PtsError ('An error occurred during writing the calibration EEPROM, check log for details')

    print("Programming OK.")    
        
    ############################################################################
    
    return card
    
if __name__ == '__main__' :
    
    import argparse

    parser = argparse.ArgumentParser(description='Start test07')
    parser.add_argument('-p', action='store_true')
    args = vars(parser.parse_args())

    if args['p']:
        main(configure_fpga=False)
    else:
        main()

