#! /bin/bash
#
# -= TODO =-
# * check if the wanted lib exist (check lib verion too)!
# * option to list all installed libraries with their versions
# * each ABI options define one specific libs (fxlibc-common, fxlibc-vhex, fxlibc-fx9860g, fxlibc-fxcg50)

# output file
confile='fxlibc.cfg'

# Build options
toolchain=sh-elf
prefix=
cflags=

# wanted Makefile
makefile='Makefile.default'

# configuration
debug=false
valgrind=false

# ABI support
support_vhex_kernel=false
support_casio_abi_fx9860=false
support_casio_abi_fxcg50=false

# format
format_static=false
format_dynamic=false

#---
# Help screen
#---
help()
{
cat << EOF
Configuration script for the fx calculator standard C library.
Usage: $0 [OPTION]...

You should build out-of-tree by creating a build directory and configuring from
there.

Debug the fxlibc
  --debug        Enable valgrind flags (-g3)
  --unit-test    Check C-functoon validity with Criterion

Build options:
  --toolchain=TRIPLET  Build with a different toolchain
                       [sh-elf-gcc] (or [gcc] when the '--unit_test' flag is set)
  --cflags=FLAGS       Additional compiler flags at end of command
  --prefix=PREFIX      Install prefix (PREFIX/lib and PREFIX/include are used)

ABI support:
  --support-vhex
    Enable the Vhex kernel support
  --support-casio-fx9860,
  --support-casio-fxcg50
    Enable the support of the Casio' ABI (used by malloc, free, ...)

    fx9860 covers all fx-9860G II-like monochromes models that support add-ins
    or can be flashed with an OS that does. This includes SH3 and SH4 machines.

    fxcg50 covers just the fx-CG 50; there is some unofficial compatibility with
    fx-CG 10/20. All of these are SH4-only.

The 'ABI support' is used to allow some part of the code, in particular the 'unistd'
part, I/O management and additionals feature. (like process, fs, ...).

Format:
    --static    Generate static libraries (default)
    --dynamic   Generate dynamic libraries (Vhex kernel dependant)

Little note for the generation of dynamic libraries. The superH toolchain currently
used (GCC) does not support the '--shared' flags when the archive is build. So we
need to create manually an archive that can be used like a shared library.

To do this we need to do several steps:
1) build the sources with the PIE mode as if it were a executable without entry point.
2) manually extract symbols defined as 'global' from the generated ELF.
3) we create "stubs": functions that will have the same name than the wanted shared
     libraries and will call internal VHEX loader primitives with the libraries
     name, function address and size, etc....Then the loader will load the shared
     function and override the "user function (stub)" to force it to jump into
     the "real" function (trampoline).
4) all generated stubs will be compiled and linked through a static lib that SHOULD
     be used in the user program which uses the "dynamic library"
EOF
  exit 0
}


#---
# Check mandatory build location
# @note:
# * You should build out-of-tree by creating a build directory and configuring
#   from there.
#---
if [ -f 'make/Makefile.default' ]; then
  echo 'error: you should configure from a build directory, like this:' >&2
  echo '  mkdir build && cd build && ../configure [options..]' >&2
  exit 1
fi


#---
# Parsing arguments
#---
for arg; do case "$arg" in
  --help | -h)
    help;;

  # debug options
  --debug)
    debug=true;;
  --unit-test)
    makefile='Malefile.unitest';;

  # build options
  --toolchain=*)
    toolchain=${arg#*=};;
  --prefix=*)
    prefix=${arg#*=};;
  --cflags=*)
    cflags=${arg#*=};;

  # ABI support
  --support-vhex)
    support_vhex_kernel=true;;
  --support-casio-abi-fx9860)
    support_casio_abi_fx9860=true;;
  --support-casio-abi-fxcg50)
    support_casio_abi_fxcg50=true;;

  # format options
  --static)
    format_static=true;;
  --dynamic)
    format_dynamic=true;;

  # error part
  *)
    echo "error: unreconized argument '$arg', giving up." >&2
    exit 1
esac; done


#---
# Check error
#---
# If no prefix is specified, install to the GCC's build folder
if [[ -z "$prefix" ]]
then
  # ask the toolchain where is his installation path
  echo "No prefix specified, let's ask the compiler:"
  echo "  Call: \"$toolchain-gcc --print-search-dirs | grep install | sed 's/install: //'\""
  if ! inst=$("$toolchain"-gcc --print-search-dirs | grep install | sed 's/install: //'); then
    echo "  Call: returned $?, giving up." >&2
    exit 1
  fi
  echo "  Got '$inst'".

  # check if the directory exist
  if [[ ! -d $inst ]]; then
    echo "Directory does not exist (or is not a directory), giving up." >&2
    exit 1
  fi
  prefix=$inst
fi


# TODO
# TODO: check if the wanted lib exist (check lib verion too)!
# TODO

#---
# Dump appropriate Makefile
# @note:
# * We have 3 makefile: normal, dynlib, unit_test
#---
dst='Makefile'
src="../make/$makefile"
if ! test $src; then
  echo "error: target makefile ($src) does not exist !" >&2
  exit 1
fi
[ $dst ] && [ "$(readlink $dst)" == $src ] && rm $dst
ln -s $src $dst


#---
# Generate the configuration file
#---
generate_config()
{
  echo 'CONFIG.CFLAGS := '
  echo 'CONFIG.TARGET := '
  echo 'CONFIG.FORMAT := '
  echo "CONFIG.TOOLCHAIN := $toolchain"
  [ "$prefix" ] && echo "CONFIG.PREFIX := $prefix"
  [ "$cflags" ] && echo "CONFIG.CFLAGS += $cflags"

  # debug / unit tests
  [ $debug = true ] && echo 'CONFIG.CFLAGS += -g3'

  # ABI support
  [ $support_vhex_kernel = true ] && echo 'CONFIG.TARGET += fxlibc-vhex'
  [ $support_casio_abi_fx9860 = true ] && echo 'CONFIG.TARGET += fxlibc-fx9860'
  [ $support_casio_abi_fxcg50 = true ] && echo 'CONFIG.TARGET += fxlibc-fxcg50'

  # formats
  [ $format_static = true ] && echo 'CONFIG.FORMAT += static'
  [ $format_dynamic = true ] && echo 'CONFIG.FORMAT += dynamic'
}
generate_config > $confile

echo "Configuration saved in $confile, ready to make!"
exit 0