#!/usr/bin/env bash

# ensure consistent behaviour
src_dir="$(dirname "$(realpath "$0")")"
source $src_dir/utils/_env.sh

echo
ninja_dev_install
echo

echo ------------------------------------
echo Creating missing runtime directories
echo ------------------------------------
mkdir -vp \
    $KRES_DEV_INSTALL_DIR/run/knot-resolver \
    $KRES_DEV_INSTALL_DIR/var/cache/knot-resolver
echo
echo ------------------------------------------------------
echo Building/installing Python components using setuptools
echo ------------------------------------------------------
# Download packages needed for offline installation into the local .wheelhouse.
[[ -e .wheelhouse ]] || \
    python -m pip download \
        --dest .wheelhouse \
        ".[prometheus,watchdog]" setuptools \
        --group all
python -m pip install -e . \
    --no-index \
    --find-links .wheelhouse

# copy native modules from build directory to source directory
shopt -s globstar
shopt -s nullglob
for d in build/lib*; do
    for f in "python/$d/"**/*.so; do
        cp -v "$f" ${f#"python/$d/"}
    done
done
shopt -u globstar
shopt -u nullglob
echo
echo ----------------------
echo Starting Knot Resolver
echo ----------------------
python3 -m knot_resolver \
    --logtarget stdout \
    --loglevel debug \
    --config "$KRES_DEV_CONFIG_FILE" \
    "$@"
