#!/command/with-contenv bashio
# shellcheck shell=bash
# ==============================================================================
# Home Assistant Community Add-on: NetBird Client
# Runs NetBird Client
# ==============================================================================
declare -a options
declare name
declare value


# Get the options configured in HASS GUI
readonly CONFIG_OLD_PATH=/homeassistant/netbird/config.json
readonly CONFIG_PATH=/config/config.json

[ -f "${CONFIG_OLD_PATH}" ] && mv "${CONFIG_OLD_PATH}" "${CONFIG_PATH}"

admin_url="$(bashio::config 'admin_url')"
management_url="$(bashio::config 'management_url')"
setup_key="$(bashio::config 'setup_key')"
hostname="$(bashio::config 'hostname')"
rosenpass="$(bashio::config 'rosenpass')"
rosenpass_permissive="$(bashio::config 'rosenpass_permissive')"
log_level="$(bashio::config 'log_level')"

options+=(--foreground-mode)
options+=(--config "${CONFIG_PATH}")
options+=(--log-file console)

if [ "${admin_url}" = "" ]; then
    bashio::log.info "Using Default Admin URL"
else
    bashio::log.info "Using ${admin_url} as Admin URL"
    options+=(--admin-url "${admin_url}")
fi

if [ "${management_url}" = "" ]; then
    bashio::log.info "Using Default Management URL"
else
    bashio::log.info "Using ${management_url} as Management URL"
    options+=(--management-url "${management_url}")
fi

if [ "${setup_key}" = "" ]; then
    bashio::log.info "No Setup Key Set"
    bashio::log.info "This client will only show up in dashboards it's already registered with."
else
    bashio::log.info "Setup Key configured (hidden for security)"
    options+=(--setup-key "${setup_key}")
fi

if [ "${hostname}" = "" ]; then
    bashio::log.info "No Hostname Set"
    bashio::log.info "This client will use the default (<docker container id>-netbird-client) as hostname in peers."
else
    bashio::log.info "Using ${hostname} as hostname"
    options+=(--hostname "${hostname}")
fi

if ! ${rosenpass}; then
    bashio::log.info "Rosenpass disabled"
    options+=(--enable-rosenpass=false)
else
    bashio::log.info "Rosenpass enabled"
    options+=(--enable-rosenpass)
    if ${rosenpass_permissive}; then
        bashio::log.info "Rosenpass permissive mode enabled"
        options+=(--rosenpass-permissive)
    fi
fi

if [ "${log_level}" = "" ] || [ "${log_level}" = "null" ]; then
    bashio::log.info "No log level Set"
    bashio::log.info "This client will use the default logging."
else
    bashio::log.info "Using ${log_level} as logging level"
    options+=(--log-level "${log_level}")
fi

# Load custom environment variables
for var in $(bashio::config 'env_vars|keys'); do
    name=$(bashio::config "env_vars[${var}].name")
    value=$(bashio::config "env_vars[${var}].value")

    # Validate that the variable name matches the expected pattern
    if [[ ! "${name}" =~ ^[A-Z_][A-Z0-9_]*$ ]]; then
        bashio::log.warning "Skipping invalid environment variable name: ${name} (must match pattern [A-Z_][A-Z0-9_]*)"
        continue
    fi

    bashio::log.info "Setting ${name} to ${value}"
    export "${name}=${value}"
done

# Workaround for DNS resolution with systemd-resolved
# NetBird checks for systemd-resolved by looking for a specific comment in /etc/resolv.conf
# This ensures NetBird can properly detect and configure DNS settings on the host
CONTENT=$(cat /etc/resolv.conf)
echo '# systemd-resolved' > /etc/resolv.conf
echo "$CONTENT" >> /etc/resolv.conf

bashio::log.info "Starting NetBird Client..."
bashio::log.info "netbird up " "${options[@]}"
netbird up "${options[@]}"
