#!/usr/bin/env python

import sys, os
import struct
from dmcfgstruct.helper import getStruct, setStruct, sizeof, odict

from dmcfgstruct.dmr3 import v3 
from dmcfgstruct.dmr3 import v4

class DMConfigFile(object):

   def __init__(self, name='config.bin'):
      self.name = name
      assert not os.path.isfile(self.name), "file exists"
      self.fd1 = open(self.name+"-master", "w")
      self.fd2 = open(self.name+"-slave", "w")
   

   def generate_completefiles(self, cont):
      # Copy the *Config structures 1:1
      print 'copy headers'
      self.both_seek(0)
      self.both_write('DMCF'+struct.pack('B', 4))
      self.both_write(cont[v3.DM_VARS_OFFSET:])
      print 'cont', cont

      # Copy the whole things before the start of
      # IO data config
      print 'copy auth data'
      self.both_write(cont[v3.DM_VARS_OFFSET:v3.DM_VARS_INPUT_NAME_ADDR-1])
      for io in xrange(1, 13):
         print 'copy IO ', io
         io2=io+12

         
         addr1=v3.getInputStatusNameAddr(io)
         addr2=v3.getInputStatusNameAddr(io2)
         size=v3.getInputStatusNameAddr(io+1)-addr1 # cause we have a 13 input for sure!
         addr=v4.getInputStatusNameAddr(io)
         self.both_seek(addr)
         self.fd1.write(cont[addr1:addr1+size])
         self.fd2.write(cont[addr2:addr2+size])


         addr1=v3.getInputNameAddr(io)
         addr2=v3.getInputNameAddr(io2)
         size=v3.getInputNameAddr(io+1)-addr1 # cause we have a 13 input for sure!
         addr=v4.getInputNameAddr(io)
         self.both_seek(addr)
         self.fd1.write(cont[addr1:addr1+size])
         self.fd2.write(cont[addr2:addr2+size])

      self.both_close()

   def both_write(self, cont):
      self.fd1.write(cont)
      self.fd2.write(cont)

   def both_close(self ):
      print 'close'
      self.fd1.close()
      self.fd2.close()

   def both_seek(self, where):
      self.fd1.seek(where)
      self.fd2.seek(where)
   

   def generate_iofiles(self,cont):
      self.both_seek(0)
      self.both_write('DMCD'+struct.pack('B', 3))
      self.both_close()

def convert(fname):
   
   cf=DMConfigFile(fname+".v4")
   


   f=open(fname, "r")
   cont=f.read()
   f.close()
   if len(cont) > 5:
      if not struct.unpack('B', cont[4])[0] == 3:
         print 'ERROR: Wrong version in source config file (', struct.unpack('B', cont[4])[0], '), nothing done'
         return 1
      print cont[0:4]
      if cont[0:4]=='DMCF':
         # Complete file
         print 'Complete config file found.'
         r1=cf.generate_completefiles(cont[5:])
         r2=cf.generate_iofiles(cont[v3.DM_VARS_STATUS_ADDR:])
         
         if r1==r2 and r1==0:
            return r1
         return 1

      elif cont[0:4]=='DMCD':
         print 'I/O Config file found'
         return generate_iofiles(cont)
      else:
         print 'ERROR: File type not recognized'
         return 1

   print 'Nothing done.'
   return 1

if __name__ == "__main__":
   fname=sys.argv[1]
   convert(fname)
