#!/bin/bash -e

SYNOPSIS="synopsis: bazel run %TARGET% -- [-h] -s STREAM"

while getopts "hs:" opt; do
  case "$opt" in
    h )
      echo $SYNOPSIS
      echo "Commit a Coverity analysis to the server."
      exit 0
      ;;
    s )
      stream="$OPTARG"
      ;;
    * )
      echo $SYNOPSIS
      exit 2
      ;;
  esac
done
shift $((OPTIND -1))

if [ -z "$stream" ]; then
  echo "error: -s followed by a stream name is required" >&2
  echo $SYNOPSIS
  exit 2
fi

analysis_dir="%ANALYSIS_DIR%"
license_file="%LICENSE_FILE%"

export VAULT_ADDR="https://vault.zooxlabs.com:8200"
# FIXME:  make it so we can use vault from all the different parts of
#         our infrastructure that will run this script
#export COV_USER="$(vault read -field=user secret/coverity/committer)"
#export COVERITY_PASSPHRASE="$(vault read -field=password secret/coverity/committer)"
export COV_USER="svc-bazel-commit"
export COVERITY_PASSPHRASE="gp4TMx3zCmWkrPw4mVKt"

if [ -z "$COV_USER" ] || [ -z "$COVERITY_PASSPHRASE" ]; then
  echo "Failed to obtain Coverity credentials" >&2
  exit 1
fi

commit_dir=$(mktemp -d --tmpdir=.)
# Committing reads the emit dir but does not change it, so symlink it.
ln -rs "$analysis_dir/emit" "$commit_dir/emit"
# Committing reads the output dir and adds new files to it, but leaves
# existing files alone, so link in the (read-only) existing files and
# make the directories writable.
cp -al "$analysis_dir/output" "$commit_dir/output"
find "$commit_dir/output" -type d -print0 | xargs -0 chmod +w

../coverity/bin/cov-commit-defects \
  --dir "$commit_dir" \
  --security-file "$license_file" \
  --url "commit://coverity.zooxlabs.com" \
  --stream "$stream"
