#!/bin/bash

if [ $# -ne 3 ]; then
    echo "Usage: $0 <name> <src dir> <obj dir>"
    exit 1;
fi

ARM=$1
SRCDIR=$2
OBJDIR=$3

APPLET=${ARM/%Arm/Applet}
BINFILE=$OBJDIR/$ARM.bin
OBJFILE=$OBJDIR/$ARM.obj
CPPFILE=$SRCDIR/$ARM.cpp
HFILE=$SRCDIR/$ARM.h
SIZE=$(stat -c%s $BINFILE)

if [ ! -f $BINFILE ]; then
    echo "$BINFILE does not exist"
    exit -1
fi

if [ ! -f $OBJFILE ]; then
    echo "$OBJFILE does not exist"
    exit -1
fi

# Generate the header file
DEFINE=_$(echo $1 | tr '[:lower:]' '[:upper:]')_H
cat > $HFILE << EOF
// WARNING!!! DO NOT EDIT - FILE GENERATED BY APPLETGEN
#ifndef $DEFINE
#define $DEFINE

#include <stdint.h>

typedef struct
{
EOF
nm -g $OBJFILE | awk '{print "    uint32_t "$3";"}' >> $HFILE
cat >> $HFILE << EOF
    uint8_t code[$SIZE];
} $1;

#endif // $DEFINE
EOF

# Generate the C file
cat > $CPPFILE << EOF
// WARNING!!! DO NOT EDIT - FILE GENERATED BY APPLETGEN
#include "$ARM.h"
#include "$APPLET.h"

$ARM $APPLET::applet = {
EOF
nm -g $OBJFILE | awk '{print "// "$3"\n0x"$1","}' >> $CPPFILE
cat >> $CPPFILE << EOF
// code
{
EOF
od -t x1 $BINFILE | awk '{for(n=2;n<=NF;n++){printf("0x"$n", ")}if(NF>1)print""}' >> $CPPFILE
cat >> $CPPFILE << EOF
}
};
EOF

