#!/usr/bin/python3
"""
#   A small script to dump the contents of a b43 initvals file
#
#   Copyright (C) 2008  Michael Buesch <m@bues.ch>
#
#   This program is free software; you can redistribute it and/or modify
#   it under the terms of the GNU General Public License version 2
#   as published by the Free Software Foundation.
#
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.
"""

import sys


def usage():
	print("b43 initvals file dumper")
	print("Prints a .initvals assembly section to stdout.")
	print("")
	print("Copyright (C) 2008-2010 Michael Buesch <m@bues.ch>")
	print("Licensed under the GNU/GPL version 2")
	print("")
	print("Usage: b43-ivaldump FILE")
	print("")
	print("FILE is the file that is going to be dumped")
	return

if len(sys.argv) != 2:
	usage()
	sys.exit(1)

filename = sys.argv[1]

try:
	ivals = open(filename, "rb").read()
except IOError as e:
	print("Could not read the initvals file: %s" % e.strerror)
	sys.exit(1)

if len(ivals) < 8:
	print("The file is too small. This can not be an initvals file.")
	sys.exit(1)

if ivals[0] != ord("i"):
	print("This is not an initvals file. (Wrong header magic).")
	sys.exit(1)

if ivals[1] != 1:
	print("Initvals file version %d is not supported by this program." % ivals[1])
	sys.exit(1)

sectname = filename.split('/')[-1]
if sectname.endswith(".fw"):
	sectname = sectname[:-3]
print(".initvals(%s)" % sectname)
idx = 8 # skip header
while idx < len(ivals):
	off_sz = ivals[idx + 0] << 8
	off_sz |= ivals[idx + 1]
	offset = off_sz & 0x7FFF
	dword = (off_sz & 0x8000) != 0

	if dword:
		data = ivals[idx + 2] << 24
		data |= ivals[idx + 3] << 16
		data |= ivals[idx + 4] << 8
		data |= ivals[idx + 5] << 0
		idx += 6
		print("\tmmio32\t0x%08X, 0x%04X" % (data, offset))
	else:
		data = ivals[idx + 2] << 8
		data |= ivals[idx + 3] << 0
		idx += 4
		print("\tmmio16\t0x%04X, 0x%04X" % (data, offset))
