#!/usr/bin/bash

set -euxo pipefail

CONFIG=/etc/ironic-inspector/ironic-inspector.conf

export IRONIC_INSPECTOR_ENABLE_DISCOVERY=${IRONIC_INSPECTOR_ENABLE_DISCOVERY:-false}
export INSPECTOR_REVERSE_PROXY_SETUP=${INSPECTOR_REVERSE_PROXY_SETUP:-false}

# shellcheck disable=SC1091
. /bin/tls-common.sh
# shellcheck disable=SC1091
. /bin/ironic-common.sh
# shellcheck disable=SC1091
. /bin/auth-common.sh

if [[ "$USE_IRONIC_INSPECTOR" == "false" ]]; then
    echo "FATAL: ironic-inspector is disabled via USE_IRONIC_INSPECTOR"
    exit 1
fi

wait_for_interface_or_ip

IRONIC_INSPECTOR_PORT=${IRONIC_INSPECTOR_ACCESS_PORT}
if [[ "$IRONIC_INSPECTOR_TLS_SETUP" == "true" ]]; then
    if [[ "${INSPECTOR_REVERSE_PROXY_SETUP}" == "true" ]] && [[ "${IRONIC_INSPECTOR_PRIVATE_PORT}" != "unix" ]]; then
        IRONIC_INSPECTOR_PORT=$IRONIC_INSPECTOR_PRIVATE_PORT
    fi
else
    export INSPECTOR_REVERSE_PROXY_SETUP="false" # If TLS is not used, we have no reason to use the reverse proxy
fi

export IRONIC_INSPECTOR_BASE_URL="${IRONIC_INSPECTOR_SCHEME}://${IRONIC_URL_HOST}:${IRONIC_INSPECTOR_PORT}"
export IRONIC_BASE_URL="${IRONIC_SCHEME}://${IRONIC_URL_HOST}:${IRONIC_ACCESS_PORT}"

build_j2_config()
{
    local CONFIG_FILE="$1"
    python3 -c 'import os; import sys; import jinja2; sys.stdout.write(jinja2.Template(sys.stdin.read()).render(env=os.environ))' < "$CONFIG_FILE.j2"
}

# Merge with the original configuration file from the package.
build_j2_config "$CONFIG" | crudini --merge "$CONFIG"

configure_inspector_auth

configure_client_basic_auth ironic "${CONFIG}"

ironic-inspector-dbsync --config-file "${CONFIG}" upgrade

if [[ "$INSPECTOR_REVERSE_PROXY_SETUP" == "false" ]] && [[ "${RESTART_CONTAINER_CERTIFICATE_UPDATED}" == "true" ]]; then
    # shellcheck disable=SC2034
    inotifywait -m -e delete_self "${IRONIC_INSPECTOR_CERT_FILE}" | while read -r file event; do
        kill $(pgrep ironic)
    done &
fi

# Make sure ironic traffic bypasses any proxies
export NO_PROXY="${NO_PROXY:-},$IRONIC_IP"

# shellcheck disable=SC2086
exec /usr/bin/ironic-inspector
