#!/bin/bash

TMPFILE="/tmp/$(basename $0)"

version="0.0.1"

SRCDIR="openocd-0.10.0"
startaddr="0x20000968"


#----------------------
function print_help() {
#----------------------
cat << EOF

Converts specific flash loaders (in form of C arrays) contained in a
a specific set of OpenOCD source files into files in Intel HEX format.

Syntax: $(basename $0) [<options>]

Options:
   -c <addr>,
   --change-address=<addr>   Change starting address to <addr>, <addr>
                             must start with "0x", e.g. "0x20000000"
                             for STM32 RAM start. Default: $startaddr

EOF
}


while [ -n "$1" ]; do
  case "$1" in
    --help|-h)
      print_help
      exit 1
      ;;
    --change-address|-c)
      if [ "${1//=//}" != "$1" ]; then
        startaddr="${1##*=}"
      else
        shift
        startaddr="$1"
      fi
      echo "Will set start address to $startaddr."
      ;;
    -*)
      echo "Unknown option '$1'."
      exit 1
      ;;
    *)
      INFILES="$INFILES $1"
      ;;
  esac
  shift
done

#-------------------------------
function check_prerequisites() {
#-------------------------------
  if [ ! -d "$SRCDIR" ]; then
    echo -e "ERROR: Cannot find '$SRCDIR', did you unpack the openocd zip file?"
    exit 1
  fi

  if ! type -p arm-none-eabi-objcopy &>/dev/null; then
    echo -e "ERROR: 'arm-none-eabi-objcopy' not found\n==> Is package 'binutils-arm-none-eabi' installed?"
    exit 1
  fi
  if ! type -p xxd &>/dev/null; then
    echo -e "ERROR: 'xxd' not found\n==> Is package 'xxd' installed?"
    exit 1
  fi
  if ! type -p grep &>/dev/null; then
    echo -e "ERROR: 'grep' not found\n==> Is package 'grep' installed?"
    exit 1
  fi
}


check_prerequisites


grepstring='static const uint8_t stm32.*_flash_write_code\[\] = '

# f1x: 0x16, 0x68, 0x00, 0x2e
# f2x: 0xd0, 0xf8, 0x00, 0x80
# l4x: 0xd0, 0xf8, 0x00, 0x80
# lx:  0x00, 0x23, 0x04, 0xe0


for file in $SRCDIR/src/flash/nor/stm32*.c; do

  echo FILE: $file
  
  outfile="$(basename $(basename $file) .c)".XEH
  outfile="${outfile^^}"
  
  grep -A9999 "$grepstring" "$file" \
  | tail -n+2 \
  | sed 's|/\*[^*]*\*/||gi' \
  | grep -vE '^['$'\t'' ]*$' \
  | grep -B99 -Fm1 '};' \
  | head -n-1 \
  | xxd -r -p > "$TMPFILE"

  arm-none-eabi-objcopy ${startaddr:+--change-addresses $startaddr} \
  -I binary -O ihex "$TMPFILE" "$outfile"

done


# --- Rename files as necessary ---


# F1X is the same for F1 and F3
cp STM32F1X.XEH STM32F1.XEH
mv STM32F1X.XEH STM32F3.XEH

# F2X is the same for F2, F4, and F7
cp STM32F2X.XEH STM32F2.XEH
cp STM32F2X.XEH STM32F4.XEH
mv STM32F2X.XEH STM32F7.XEH


cat << EOF

The following files have been generated by this script:

STM32F1.XEH
STM32F2.XEH
STM32F3.XEH
STM32F4.XEH
STM32F7.XEH
STM32L4X.XEH
STM32LX.XEH

EOF
