#!/bin/bash

set -e

out=$("$1" 'map(select(.["file"] | contains ("cc_cflags_probe.c"))) | first | .["command"]' < compile_commands.json)
out=${out#\"}
out=${out%\"}
args=($out)

idx=0
cc=${args[idx]}
if [ "$cc" = "ccache" ]; then
    idx=$((idx+1))
    cc="$cc ${args[idx]}"
fi

if [ "$cc" = "sccache" ]; then
    idx=$((idx+1))
    cc="$cc ${args[idx]}"
fi

if [ "$cc" = "ccache" ]; then
    idx=$((idx+1))
    cc="$cc ${args[idx]}"
fi

if [ "$cc" = "sccache" ]; then
    idx=$((idx+1))
    cc="$cc ${args[idx]}"
fi

declare -a cflags=()

for arg in ${args[@]:(idx+1)}; do
    case $arg in
	-I*|-M*|-o|-c) ;;
	-*) cflags+="$arg ";;
    esac
done

make_out=$(env CC="$cc" CFLAGS="$cflags" BUILD_STATIC_ONLY=y DESTDIR=. "$2" install -C "$3" -j"$4")
exit $?
