#!/bin/sh
# Copyright Polymath. All rights reserved.
set -eu
sample=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
repo=$(CDPATH= cd -- "$sample/../.." && pwd)
if [ -n "${VELA_SDK_ROOT:-}" ]; then
    include=$VELA_SDK_ROOT/include
    builder=$VELA_SDK_ROOT/bin/vela-sdk
    action=package
else
    include=${VELA_SDK_INCLUDE:-$repo/sdk/native/include}
    builder=${VELA_APP_BUILDER:-$repo/platform/app-manager/vela-app}
    action=build
fi
if [ ! -f "$include/vela/card.h" ] || [ ! -x "$builder" ]; then
    echo 'Set VELA_SDK_ROOT to the extracted Vela developer SDK directory.' >&2
    exit 1
fi
mvn --batch-mode --strict-checksums -f "$sample/pom.xml" "$@" package
target="$sample/vela/target"
"${CC:-cc}" -std=gnu11 -O2 -ffunction-sections -fdata-sections -static -Wl,--gc-sections -s \
    -I"$sample/vela" -I"$include" \
    "$target/generated-c/all.c" -lm -o "$target/interval-coach"
# The package builder creates a new file each time; publish only after validation.
out=$(mktemp -d "$target/package.XXXXXXXX")
trap 'rm -rf -- "$out"' EXIT
"$builder" "$action" "$sample/vela/manifest.json" \
    "$target/interval-coach" "$out/interval-coach.vapp"
mv -- "$out/interval-coach.vapp" "$target/interval-coach.vapp"
