#!/bin/bash -e

set -o pipefail

config_tar="$1"
emit_db="$2"
emit_wd="$3"
cc="$4"
shift 4

config_dir=$(mktemp -d)
emit_dir=$(mktemp -d)
cov_translate_tmpdir=$(mktemp -d)

tar xf "$config_tar" -C "$config_dir" --warning=no-timestamp

# See if the compiler is a wrapper script and find the real one if it is
if head -c 20 "$cc" | grep -q '^#!/bin/[a-z]*sh'; then
  wrapped_cc=$(grep -m 1 '^exec' "$cc" | sed 's/exec *\([^ ]*\).*/\1/')
  test -n "$wrapped_cc" && cc="$wrapped_cc"
fi

# Silence complaints about the compiler's absolute path changing
find "$config_dir" -name "*.xml" -print0 \
  | xargs -0 sed -i "s#<comp_dir>.*</comp_dir>#<comp_dir>$(dirname $cc)</comp_dir>#"

# cov-translate complains about args that should be marked as required
# if we don't strip out options like -std=c++11.
external/coverity/bin/cov-translate \
  --verbose 0 \
  --emit-complementary-info \
  --config "$config_dir/coverity_config.xml" \
  --tmpdir "$cov_translate_tmpdir" \
  --dir "$emit_dir" \
  -- "$cc" $(echo "$@" | sed 's/-std=[^ ]*//g') \
  | sed '/Emit for file .* complete./d'
mv "$emit_dir/emit/$(hostname)/emit-db" "$emit_db"
rm -rf "$config_dir" "$emit_dir"

pwd > "$emit_wd"
