#!/bin/sh -e

emit_dir="$1"
emit_db_list_file="$2"
output_db="$3"
shift 3

# The Coverity emit-db looks like the following:
#   emit/version                      (a constant)
#   emit/$hostname/emit-db            (an SQLite db with intermediates)
#   emit/$hostname/emit-db.lock       (a read lock with a hostname)
#   emit/$hostname/emit-db.write-lock (a write lock with a hostname)
#
# Machines write to hostname-specific directories because distributed
# builds are accomplished by pointing every machine at a single directory
# on shared storage.  After the distributed build is done one must
# combine databases from other machines into that of the machine doing
# the analysis.
#
# Here we fabricate this structure by treating each emit-db file produced
# via Bazel actions as if it was written by a separate "host", then feed
# that to Coverity for combination.

mkdir --parent "$emit_dir/emit"
# Version 2021.03
echo 299 > "$emit_dir/emit/version"
while read emit_db_file; do
  [ -n "$emit_db_file" ] && ln "$emit_db_file" "$(mktemp --directory --tmpdir=$emit_dir/emit)/emit-db"
done < "$emit_db_list_file"

external/coverity/bin/cov-manage-emit --dir "$emit_dir" add-other-hosts
rm -rf "$emit_dir"/emit/tmp.*
mv -f "$emit_dir"/emit/*/emit-db "$output_db"
