#!/usr/bin/env bash

set -euo pipefail

source_root=$(CDPATH= cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)

mkdir -p "$source_root/build"

compiler=${CC:-cc}
compile_flags=(-std=c11 -O2 -Wall -Wextra -Werror -pedantic)
compile_helper () {
  local source_path=$1
  local target_path=$2

  if [[ ${AUTOLITH_BUILD_STATIC_NATIVE:-} == 1 ]]; then
    "$compiler" "${compile_flags[@]}" -static -no-pie \
      "$source_path" -o "$target_path"
  else
    "$compiler" "${compile_flags[@]}" \
      "$source_path" -o "$target_path"
  fi
}

compile_helper "$source_root/helper/cl-exec-sandbox-process-group.c" \
  "$source_root/build/cl-exec-sandbox-process-group"

if [[ $(uname -s) == Linux ]]; then
  compile_helper "$source_root/helper/cl-exec-sandbox-helper.c" \
    "$source_root/build/cl-exec-sandbox-helper"
fi
