#! /usr/bin/env bash

# This script is a convenience wrapper for invoking programs that use the
# standard Clang libtooling command-line interface.
# This script locates the Clang built-in include directory and then runs
# the specified program with an extra command-line option specifying this
# directory.

################################################################################
# Functions.
################################################################################

eecho()
{
	echo "$@" 1>&2
}

panic()
{
	echo "ERROR: $*" 1>&2
	exit 1
}

usage()
{
	echo "BAD USAGE: $*" 1>&2
	exit 2
}

################################################################################
# Process command-line arguments.
################################################################################

verbose="${CL_DEBUG_LEVEL:-0}"
#verbose=1

if [ $# -lt 1 ]; then
	usage "no program specified"
fi

program="$1"
shift 1
args=("$@")

################################################################################
# Determine key pathnames.
################################################################################

self_program="$(realpath "$0")" || \
  panic "dirname failed"
self_dir="$(dirname "$self_program")" || \
  panic "realpath failed"
get_clang_inc_dir="$self_dir/get_clang_include_dir"

################################################################################
# Find the Clang built-in include directory.
################################################################################

if [ "$verbose" -ge 1 ]; then
	eecho "RUNNING: $get_clang_inc_dir"
fi
clang_inc_dir="$("$get_clang_inc_dir")" || \
  panic "cannot determine Clang built-in include directory"

################################################################################
# Run the specified program with an extra option for the Clang built-in
# include directory.
################################################################################

command=("$program" "-extra-arg=-I$clang_inc_dir" "${args[@]}")
if [ "$verbose" -ge 1 ]; then
	eecho "RUNNING: ${command[*]}"
fi
exec "${command[@]}"
