#!/bin/bash -e

if [[ ! ($# -ge 1 && $# -le 3) ]]; then
  echo "Usage: $0 [--debug] LCP_FILE [SLK_SERIALIZE]"
  echo "Convert a LCP_FILE to C++ header file and output to stdout."
  echo "If SLK_SERIALIZE is provided, then SLK serialization is generated."
  exit 1
fi

debug=false
if [[ "$1" == "--debug" ]]; then
  debug=true
  shift
fi

if [[ ! -r "$1" ]]; then
  echo "File '$1' doesn't exist or isn't readable"
  exit 1
fi

lcp_file=`realpath $1`
script_dir="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

quicklisp_install_dir="$HOME/quicklisp"
if [[ -v QUICKLISP_HOME ]]; then
  quicklisp_install_dir="${QUICKLISP_HOME}"
fi

slk_serialize=""
if [[ "$2" == "SLK_SERIALIZE" ]]; then
  slk_serialize=":slk-serialize-p t"
fi

if [[ $debug == "true" ]]; then
  echo \
  "
  (load \"${quicklisp_install_dir}/setup.lisp\")
  (ql:quickload :lcp :silent t)
  (let ((*debugger-hook* #'lcp.debug:lcp-debugger-hook))
    (lcp:process-lcp-file \"$lcp_file\" $slk_serialize))
  " | sbcl --noinform --noprint
else
  echo \
  "
  (load \"${quicklisp_install_dir}/setup.lisp\")
  (ql:quickload :lcp :silent t)
  (lcp:process-lcp-file \"$lcp_file\" $slk_serialize)
  " | sbcl --script
fi

filename=`basename $lcp_file .lcp`
hpp_file="$(dirname $lcp_file)/$filename.hpp"
clang-format -style=file -i $hpp_file

if [[ -w  "$lcp_file.cpp" ]]; then
  clang-format -style=file -i "$lcp_file.cpp"
fi