#!/usr/bin/python3
""" Decode the header of dsp bin file """
import sys
import os
import re
import struct

def print_header(s,a,v,c):
    if v < 51200: # decimal version < 5.12.00
        vmaj = v / 10000
        v = v - vmaj * 10000
        vmin = v / 100
        v = v - vmin * 100
        vtype = 'dec'
    else: # hex version >= 0.200.0
        vmaj = v >> 16
        vmin = (v >> 8) & 0xFF
        v = v & 0xFF
        vtype = 'hex'

    print('AX%x, %s version %d.%02d.%02d, size %d, checksum 0x%X' % (a, vtype, vmaj,vmin,v,s,c))

def find_header(fname):
    print(fname, end=' ')
    f = open(fname, 'rb')
    h = f.read(20)
    got_data = False

    (s,t,a,v,c) = struct.unpack('I4sIII',h)
    if t == 'CODE':
        print('ASI CODE header: ', end=' ')
        print_header(s, a, v, c)
        got_data = True

    f.seek(-20, 2)
    h = f.read(20)
    c, s, v, a, t = struct.unpack('4I4s',h)
    if t == 'CODE':
        print('ASI CODE tailer: ', end=' ')
        print_header(s, a, v, c)
        got_data = True

    if not got_data:
        print('No ASI metadata found')

    f.close()


def scandir(d):
    d = os.path.abspath(os.path.dirname(d))
    test = re.compile("dsp[0-9]+.*\.bin")
    files = list(filter(test.search, os.listdir(d)))

    test = re.compile("asi[0-9]+.*\.firmware")
    files += list(filter(test.search, os.listdir(d)))

    test = re.compile("asi[0-9]+.*\.bootloader")
    files += list(filter(test.search, os.listdir(d)))

    list(map(find_header,files))

if __name__ == "__main__":
    if sys.argv[1].endswith('/'):
        scandir(sys.argv[1])
    else:
        find_header(sys.argv[1])
