#!/bin/sh

# description
# * compiles the sc source code to c
# dependencies
# * sph-sc
# * clang-format

sc_compiler=./submodules/sph-sc/exe/sc
s=source/sc
sm="$s/main"
c=source/c-precompiled
export SC_LOAD_PATH="$PWD/$s:$PWD/$s/foreign"
export GUILE_LOAD_PATH="$PWD/submodules/sph-sc/modules:$PWD/submodules/sph-lib/modules:$GUILE_LOAD_PATH"

format_c() {
  clang-format -i "$@"
}

copy_example_config() {
  # the config file is not versioned so that users can customise it
  if [ ! -f "$sm/config.sc" ]
  then
    cp "$sm/config.sc.example" "$sm/config.sc"
  fi
}

copy_submodules() {
  # copy code files from submodules.
  # to not have the whole submodule in the source directory
  a=submodules/sph-sc-lib/source/sc
  b="$a/sph"
  f="$s/foreign"
  mkdir -p "$f/sph" &&
  cp --update --target-directory="$f" "$a/sph.sc" &&
  cp --update --target-directory="$f/sph" \
    "$b/status.sc" "$b/mi-list.sc" "$b/imht-set.sc" "$b/one.sc"
}

compile_sc_libsph_dg() {
  # create the c source code
  copy_example_config &&
  copy_submodules &&
  $sc_compiler "$sm/main.sc" "$c/main.c" &&
  $sc_compiler "$sm/sph-dg.sc" "$c/sph-dg.c" &&
  format_c "$c/main.c" &&
  format_c "$c/sph-dg.c"
}

compile_sc_test() {
  $sc_compiler "$s/test/main.sc" "$c/test-main.c" &&
  format_c "$c/test-main.c"
}

mkdir -p "$c" &&
compile_sc_libsph_dg $@ &&
compile_sc_test $@ &&
chmod 644 "$c"/*