#!/bin/bash

set -eu
set -o pipefail

. "$AUTOBUILD_ROOT/lib/log.sh"

INSTALL_COMMAND=(sudo --non-interactive DEBIAN_FRONTEND=noninteractive apt-get install -y --no-remove --no-install-recommends --)

sudo --non-interactive apt-get update

"${INSTALL_COMMAND[@]}" unzip

source /etc/os-release || source /usr/lib/os-release

DEPTRACE_SERVER="$AUTOBUILD_ROOT/$CODEQL_PLATFORM/deptrace-server"
CODEQL_DEPTRACE_DB="$AUTOBUILD_TMP_DIR/deptrace-db.txt"
CODEQL_DEPTRACE_DB_ARCHIVE="deptrace-db-$ID-$VERSION_CODENAME.zip"
DEPTRACE_PID_FILE="$AUTOBUILD_TMP_DIR/deptrace.pid"

if [[ -n "${CODEQL_EXTRACTOR_CPP_LOCAL_DEPTRACE_DB:-}" ]]; then
  mkdir -p "$(dirname "$CODEQL_EXTRACTOR_CPP_LOCAL_DEPTRACE_DB")"
  ln -sf "$(realpath --canonicalize-missing "$CODEQL_EXTRACTOR_CPP_LOCAL_DEPTRACE_DB")" "$CODEQL_DEPTRACE_DB"
  if [[ -s "$CODEQL_EXTRACTOR_CPP_LOCAL_DEPTRACE_DB" ]]; then
    log "using provided deptrace DB $CODEQL_EXTRACTOR_CPP_LOCAL_DEPTRACE_DB"
  else
    # this is a request to populate the deptrace DB in-place
    if [[ "$ID" != "ubuntu" ]]; then
      log "deptrace is currently only supported on ubuntu"
      exit 1
    fi
    log "populating deptrace package database"
    "${INSTALL_COMMAND[@]}" ca-certificates curl perl-modules
    "$AUTOBUILD_ROOT/deptrace-make-db" "$CODEQL_DEPTRACE_DB"
  fi
elif [[ -f "$AUTOBUILD_ROOT/$CODEQL_DEPTRACE_DB_ARCHIVE" ]]; then
  log "using built-in deptrace DB"
  unzip -p "$AUTOBUILD_ROOT/$CODEQL_DEPTRACE_DB_ARCHIVE" deptrace-db.txt > "$CODEQL_DEPTRACE_DB"
else
  log "deptrace not supported in $ID $VERSION_ID"
  exit 1
fi
(grep '[Cc]onfig\.cmake$' "$CODEQL_DEPTRACE_DB" || true) > "$CODEQL_DEPTRACE_CMAKE_CONFIGS"

"$DEPTRACE_SERVER" \
  --pid_file="$DEPTRACE_PID_FILE" \
  --detach "$CODEQL_DEPTRACE_DB" \
  --list_file "$AUTOBUILD_TMP_DIR/deptrace.list" \
  -- "${INSTALL_COMMAND[@]}" \
  >"$CODEQL_EXTRACTOR_CPP_LOG_DIR/deptrace.log" 2>&1
log "launched deptrace server"
