#!/usr/bin/env bash

set -e -o pipefail

# this is a special command to allow inspection on this container
if [[ "$1" == "inspect" ]]; then
  shift
  exec "$@"
fi

cd "$(dirname "${BASH_SOURCE[0]}")"

LNTOP_HOME_DIR=.lntop
LNTOP_CONFIG="$LNTOP_HOME_DIR/config.toml"
LNTOP_CONFIG_TEMPLATE="$LNTOP_HOME_DIR/config-template.toml"
LNTOP_HOST_GID=${LNTOP_HOST_GID:?required}
LNTOP_HOST_UID=${LNTOP_HOST_UID:?required}

# make sure lntop's home dir exists (should be mapped to host via a volume)
if [[ ! -d "$LNTOP_HOME_DIR" ]]; then
  mkdir -p "$LNTOP_HOME_DIR"
  chown ${LNTOP_HOST_UID}:${LNTOP_HOST_GID} "$LNTOP_HOME_DIR"
fi

eval_template() {
  local template_file=$1
  eval "cat <<TEMPLATE_EOF_MARKER
$(<${template_file})
TEMPLATE_EOF_MARKER
" 2> /dev/null
}

# stage template file only if it does not already exist
if [[ ! -e "$LNTOP_CONFIG_TEMPLATE" ]]; then
  cp initial-config-template.toml "$LNTOP_CONFIG_TEMPLATE"
fi

# we dynamically prepare config from template by baking in env variables
echo "# !!! GENERATED !!! DO NOT EDIT THIS FILE, EDIT config-template.toml INSTEAD" > "$LNTOP_CONFIG"
eval_template initial-config-template.toml >> "$LNTOP_CONFIG"

exec lntop "$@"