#!   /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 ad9510 import *
from adf4002 import *
from dac import *
from sys import __stdout__


from spec_identification import *


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

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

def main (card=None, default_directory='.',suite=None):
    

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

    # init spec
    carrier=spec( FIRMWARE_PATH, specid, True );
     
    #configure main clock source
#     sys_pll = ad9516(carrier);

    print("Programming SDB filesystem into mezzanine's EEPROM...")    

    #subprocess.call(["./%s/gensdbfs %s/sdbfs %s/fd-eeprom.bin" % (default_directory, default_directory, default_directory)])
    returnval = os.system("./%s/gensdbfs %s/sdbfs %s/fd-eeprom.bin" % (default_directory, default_directory, default_directory))
    
    if (returnval != 0):
        print "swapfile not enabled, run out of memory"
        raise PtsError ('An error occurred during writing the calibration EEPROM, check log for details')
    else:
        print("eeprom file created in %s" % (default_directory))

        # wait for file to be visible on disk
        time.sleep(1)

        # run eeprom writing procedure
        return_value = carrier.write_eeprom_from_file("%s/fd-eeprom.bin" % default_directory, 0)

        print("eeprom file written to eeprom")

        eeprom = "log_fmcdac600m12b1chadds/eeprom/fd-eeprom_%s.bin" % datetime.datetime.now()
        print "%s/fd-eeprom.bin" % default_directory, "%s" % eeprom
        os.rename("%s/fd-eeprom.bin" % default_directory, "%s" % eeprom )
        print("eeprom file moved to %s" % eeprom)

        #os.remove("%s/fd-eeprom.bin" % (default_directory))

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

        print("Programming OK.")    
    
    # restore stderr and display debug information from file
    
    ############################################################################
    
    return card
    
if __name__ == '__main__' :
    main()
