#!/usr/bin/with-contenv bashio
# vim: ft=bash
# shellcheck shell=bash
# ==============================================================================
# Start matter-server service
# ==============================================================================
bashio::log.info "Starting Matter Server..."

declare server_port
declare log_level
declare log_level_sdk
declare primary_interface
declare matter_server_version
declare chip_version
matter_server_args=()
extra_args=()

if ! bashio::config.exists log_level; then
  bashio::log.magenta 'No log_level set in config, fallback to info'
fi
log_level=$(bashio::string.lower "$(bashio::config log_level info)")

# Make Matter SDK log level currently default to error
log_level_sdk=$(bashio::string.lower "$(bashio::config log_level_sdk error)")

if bashio::config.has_value "matter_server_version"; then
  matter_server_version=$(bashio::config 'matter_server_version')
  bashio::log.info "Installing Python Matter Server ${matter_server_version}"
  # shellcheck disable=SC2102
  pip3 install --pre python-matter-server[server]=="${matter_server_version}"
elif bashio::config.true "beta"; then
  bashio::log.info 'Upgrading Python Matter Server to latest pre-release'
  # shellcheck disable=SC2102
  pip3 install --upgrade --pre python-matter-server[server]
fi

if bashio::config.has_value "matter_sdk_wheels_version"; then
  chip_version=$(bashio::config 'matter_sdk_wheels_version')
  bashio::log.info "Installing Matter SDK ${chip_version}"
  pip3 install --pre --no-dependencies \
    home-assistant-chip-clusters=="${chip_version}" \
    home-assistant-chip-core=="${chip_version}"
fi

# Bind to internal hassio network only unless user requests to expose
server_port="$(bashio::addon.port 5580)"
if ! bashio::var.has_value "${server_port}"; then
    server_port=5580
    extra_args+=('--listen-address' "$(bashio::addon.ip_address)")
fi

if bashio::config.true "enable_test_net_dcl"; then
    extra_args+=('--enable-test-net-dcl')
fi

primary_interface="$(bashio::api.supervisor 'GET' '/network/info' '' 'first(.interfaces[] | select (.primary == true)) .interface')"

# Try fallback method (e.g. in case NetworkManager is not available)
# shellcheck disable=SC2086
if [ -z ${primary_interface} ]; then
  bashio::log.warning 'Trying fallback method to determine primary interface'
  primary_interface="$(ip --json route show default | jq --raw-output '.[0].dev')"
fi

# shellcheck disable=SC2086
if [ -z ${primary_interface} ] || [ ${primary_interface} == "null" ]; then
    bashio::exit.nok "No primary network interface found!"
fi

if bashio::config.has_value "bluetooth_adapter_id"; then
  # shellcheck disable=SC2207
  extra_args+=('--bluetooth-adapter' $(bashio::config 'bluetooth_adapter_id'))
fi

if bashio::config.has_value "matter_server_args"; then
  # shellcheck disable=SC2207
  extra_args+=($(bashio::config 'matter_server_args'))
fi

bashio::log.info "Using '${primary_interface}' as primary network interface."

# Send out discovery information to Home Assistant
/etc/s6-overlay/scripts/matter-server-discovery &

# shellcheck disable=SC2164
cd /root

# shellcheck disable=SC2206
matter_server_args+=(
  '--storage-path' "/data"
  '--port' "${server_port}"
  '--log-level' "${log_level}"
  '--log-level-sdk' "${log_level_sdk}"
  '--primary-interface' "${primary_interface}"
  '--paa-root-cert-dir' "/data/credentials"
  '--ota-provider-dir' "/config/updates"
  '--fabricid' 2
  '--vendorid' 4939
  ${extra_args[@]}
)

if bashio::config.true "beta"; then
    exec /usr/bin/gdb --quiet -ex="set confirm off" -ex run -ex backtrace -ex "quit \$_exitcode" --args /usr/local/bin/python \
         /usr/local/bin/matter-server "${matter_server_args[@]}"
else
    exec /usr/local/bin/matter-server "${matter_server_args[@]}"
fi
