#!/bin/sh
set -e

DOWNLOAD_PATH=/windows/lenovo/6quj08us

SRCDIR=$(pwd)

if [ "$#" -lt 1 ]; then
	echo "Usage: $0 [-nolzint] <file.rom> [<output.rom>]"
	exit 1
fi

FILE=
OUTPUT_FILE=OUTPUT.MOD
LZINT="COMPRESS  LZINT		# Use LZINT when compressing modules"

while [ "$#" -gt 0 ]; do
	case $1 in
		-nolzint)
			LZINT=""
			;;
		*)
			if [ -z "$FILE" ]; then
				FILE="$1"
			else
				OUTPUT_FILE="$1"
			fi
			;;
	esac
	shift
done

#rm logo.mod
# if ! chkbmp logo.bmp
#	echo "LOGO.BMP file is not found or is not correct."
# fi

TMPDIR=$(mktemp -d)

trap '[ -n "$TMPDIR" ] && rm -rf "$TMPDIR"' EXIT

FNAME=$(basename "$FILE")

# compose a .scr on the fly
cat > "$TMPDIR/bios.scr" <<EOF
BANKS -N:1 -S:256	# Flash accessed as one(1), 8192 KByte (64Mb) bank.
$LZINT
BOOTBLOCK -S:128	# (J) PSI style, no BB.BIN needed
BIOSCODE $FNAME
PSI -PLACE:"BOOTBLOCK" -ALIGN:TOP -COMPRESS:NO  ceimain.bin
EOF

cp "$DOWNLOAD_PATH"/ceimain.bin "$TMPDIR"/
cp "$FILE" "$TMPDIR"/
cd "$TMPDIR"
wine "$DOWNLOAD_PATH"/fp.exe bios.scr
wine "$DOWNLOAD_PATH"/fi.exe bios.scr
wine "$DOWNLOAD_PATH"/ROM2MOD.EXE BIOS.ROM OUTPUT.MOD
cd "$SRCDIR"

cp "$TMPDIR/OUTPUT.MOD" "$OUTPUT_FILE"

exit 0
