#!/bin/bash

set -euo pipefail

echo "Starting dbt run script ..."
sleep 5 # Sleep for five seconds to allow sidecar containers to finish logging/starting

export DBT_PROFILES_DIR="/var/app/profiles/snowflake_ssh_auth"

cd /var/app

DBT_EXEC="/var/env/bin/dbt"
DBT_SELECT_MODELS=${DBT_SELECT_MODELS:-""}
DBT_EXCLUDE_MODELS=${DBT_EXCLUDE_MODELS:-""}
DBT_TARGET=${DBT_TARGET:-"test"}
DBT_FULL_REFRESH=${DBT_FULL_REFRESH:-"false"}

echo "Installing DBT dependencies ..."
${DBT_EXEC} deps

if [ -z "${DBT_SELECT_MODELS}" ]; then
  echo "No models selected. skipping run command"
  exit 0
fi

echo "Running dbt run command ..."
run_command=()
run_command+=("${DBT_EXEC}")
run_command+=("run")
run_command+=("--target")
run_command+=("${DBT_TARGET}")
run_command+=("--select")
run_command+=("${DBT_SELECT_MODELS}")
if [ "${DBT_FULL_REFRESH}" = "true" ]; then
  run_command+=("--full-refresh")
fi
if [ -n "${DBT_EXCLUDE_MODELS}" ]; then
  run_command+=("--exclude")
  run_command+=("${DBT_EXCLUDE_MODELS}")
fi

# Add warn-error-options to treat NoNodesForSelectionCriteria as error
run_command+=("--warn-error-options")
run_command+=("{\"error\": [\"NoNodesForSelectionCriteria\"]}")

echo "Running dbt run command: ${run_command[*]}"
exec "${run_command[@]}"
