#!/usr/bin/env bash

# Defaults
BIN="/usr/bin/JFlashExe"
PROJECT=""
APPLICATION=""
BOOTLOADER=""
LOG="/tmp/jflash_$(date +%s).log"
HEADLESS=0

# When running in CI pipeline JFlash requires an X session!
_XTERM_HACK="-screen 0 1400x900x24 +extension RANDR"

# Usage or Help message
usage() {
  cat <<EOF >&2
Segger JFlash tool

Usage: $(basename "$0")  [--headless] [--help]

Options:
  -h, --help
          Output usage messsage and exit.
  -l, --headless
          Runs JFlashExe with an X client. Needed for CI server execution.
  -a, --application
          Path to application for flashing.
  -b, --bootloader
          Path to bootloader for flashing.
  -p, --project
          Path to JLink project file.
EOF
  exit 1
}

# Transform long options to short ones
for arg in "$@"; do
  shift
  case "$arg" in
    '--help')         set -- "$@" '-h'   ;;
    '--headless')     set -- "$@" '-l'   ;;
    '--application')  set -- "$@" '-a'   ;;
    '--bootloader')   set -- "$@" '-b'   ;;
    '--project')      set -- "$@" '-p'   ;;
    *)                set -- "$@" "$arg" ;;
  esac
done

# Parse short options
OPTIND=1
while getopts "a:p:b:hl" opt
do
  case "$opt" in
    'h') usage; exit 0 ;;
    'l') HEADLESS=1 ;;
    'a') APPLICATION=$OPTARG ;;
    'p') PROJECT=$OPTARG ;;
    'b') BOOTLOADER=$OPTARG ;;
    '?') usage; exit 1 ;;
  esac
done
shift "$(expr $OPTIND - 1)" # remove options from positional parameters

# Introspection - show invocation
_IN_HEADLESS_MODE="" # Used to tell user if in headless mode
if [[ $HEADLESS -eq 1 ]] ; then _IN_HEADLESS_MODE=" in headless mode" ; fi;
cat <<EOF >&2
Running Segger JFlash tool$_IN_HEADLESS_MODE with arguments

  Application:  $APPLICATION
  Bootloader:   $BOOTLOADER
  Project:      $PROJECT

EOF

## USB Flash with Segger J-Link Plus Compact
INVOCATION="${BIN} -openprj${PROJECT} -open${BOOTLOADER} -merge${APPLICATION},0x4000 -jflashlog${LOG} -auto -hide -startapp -exit"
if [[ $HEADLESS -eq 1 ]]
then
  xvfb-run -a -s "${_XTERM_HACK}" -- `echo "${INVOCATION}"`
else
  `echo "${INVOCATION}"`
fi
echo "Log file written to ${LOG}"
cat "${LOG}"
