#!/bin/bash

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

build_kresd

echo
echo Building Knot Resolver Manager native extensions
echo ------------------------------------------------
poetry build
# copy native modules from build directory to source directory
shopt -s globstar
shopt -s nullglob
for d in build/lib*; do
    for f in "$d/"**/*.so; do
        cp -v "$f" ${f#"$d/"}
    done
done
shopt -u globstar
shopt -u nullglob

echo
echo Knot Manager API is accessible on http://localhost:5000
echo -------------------------------------------------------

# create runtime directories
if [ -z "${KRES_MANAGER_RUNTIME:-}" ]; then
    KRES_MANAGER_RUNTIME="etc/knot-resolver"
fi
mkdir -p "$KRES_MANAGER_RUNTIME/runtime" "$KRES_MANAGER_RUNTIME/cache"

if [ -z "${KRES_MANAGER_CONFIG:-}" ]; then
    KRES_MANAGER_CONFIG="$KRES_MANAGER_RUNTIME/config.dev.yaml"
fi

if [ -z "${KRES_MANAGER_API_SOCK:-}" ]; then
    KRES_MANAGER_API_SOCK="$KRES_MANAGER_RUNTIME/manager.sock"
fi

export KRES_MANAGER_CONFIG
export KRES_MANAGER_API_SOCK
python3 -m knot_resolver_manager $@
