#!/usr/bin/env bash
# Builds libdivecomputer plus dcweb.c into WebAssembly: site/lab/dc/dc.js and dc.wasm (with dcio.js copied next to them).
# Needs Emscripten: run emsdk_env first so emcc is on the PATH (on Windows in Git Bash, EMCC=emcc.bat).
# libdivecomputer's source is expected in ~/dc-build/libdivecomputer (git clone https://github.com/libdivecomputer/libdivecomputer),
# or set LDC. It's compiled straight from its .c files, so its autotools build isn't needed.
set -euo pipefail
HERE=$(cd "$(dirname "$0")" && pwd)
LDC=${LDC:-$HOME/dc-build/libdivecomputer}
EMCC=${EMCC:-emcc}
OUT="$HERE/../../site/dc"
GEN="$HERE/build/gen"
mkdir -p "$GEN/libdivecomputer" "$OUT"

# version.h from its template, the version numbers from configure.ac
v() { sed -n "s/^m4_define(\[dc_version_$1\],\[\(.*\)\])/\1/p" "$LDC/configure.ac"; }
MAJ=$(v major); MIN=$(v minor); MIC=$(v micro); SUF=$(v suffix)
VER="$MAJ.$MIN.$MIC${SUF:+-$SUF}"
sed -e "s/@DC_VERSION@/$VER/" -e "s/@DC_VERSION_MAJOR@/$MAJ/" -e "s/@DC_VERSION_MINOR@/$MIN/" -e "s/@DC_VERSION_MICRO@/$MIC/" \
  "$LDC/include/libdivecomputer/version.h.in" > "$GEN/libdivecomputer/version.h"

# what configure would find on a POSIX system; no USB, IrDA, classic Bluetooth or HID libraries (the browser does the I/O)
cat > "$GEN/config.h" <<EOF
#define ENABLE_LOGGING 1
#define HAVE_GMTIME_R 1
#define HAVE_LOCALTIME_R 1
#define HAVE_TIMEGM 1
#define HAVE_STRUCT_TM_TM_GMTOFF 1
#define HAVE_CLOCK_GETTIME 1
#define HAVE_PTHREAD_H 1
${SUF:+#define HAVE_VERSION_SUFFIX 1}
#define VERSION "$VER"
#define PACKAGE "libdivecomputer"
EOF

# the library's git revision, as its own build writes it
REV=$(git -C "$LDC" rev-parse --verify HEAD 2>/dev/null || echo unknown)
echo "#define DC_VERSION_REVISION \"$REV\"" > "$GEN/revision.h"

SRC=()
for f in "$LDC"/src/*.c; do
  case "$(basename "$f")" in serial_win32.c|serial_posix.c) continue ;; esac
  SRC+=("$f")
done

echo "libdivecomputer $VER: ${#SRC[@]} files"
"$EMCC" -O2 -DHAVE_CONFIG_H -I"$GEN" -I"$GEN/libdivecomputer/.." -I"$LDC/include" -I"$LDC/src" \
  -Wno-deprecated-declarations -Wno-macro-redefined \
  "${SRC[@]}" "$HERE/dcweb.c" \
  -sMODULARIZE=1 -sEXPORT_ES6=1 -sEXPORT_NAME=createDC -sENVIRONMENT=web \
  -sASYNCIFY=1 -sASYNCIFY_STACK_SIZE=65536 -sALLOW_MEMORY_GROWTH=1 \
  -sEXPORTED_FUNCTIONS=_dcw_list,_dcw_download,_dcw_version,_dcw_free,_malloc,_free \
  -sEXPORTED_RUNTIME_METHODS=ccall,UTF8ToString,stringToUTF8,HEAPU8 \
  -o "$OUT/dc.js"
cp "$HERE/dcio.js" "$OUT/dcio.js"
ls -l "$OUT"
