#!/usr/bin/with-contenv bashio
# ==============================================================================
# Start OpenZWave service for zwave radio
# ==============================================================================
# shellcheck disable=SC1091
source /usr/lib/mqtt_helper.sh

export MQTT_PASSWORD
export OZW_NETWORK_KEY

MQTT_PASSWORD="$(bashio::jq /data/auth.json '.ozw_password')"
OZW_CONFIG=/data/ozw/config
OZW_DEVICE=$(bashio::config 'device')
OZW_INSTANCE=1
OZW_NETWORK_KEY=$(bashio::config 'network_key')

# Set custom instance ID if configured
if bashio::config.has_value 'instance'; then
    OZW_INSTANCE=$(bashio::config 'instance')
fi

# Wait until mosqitto is up and running
bashio::log.info "Starting OpenZWave..."
bashio::net.wait_for 1883

# Ensure local MQTT server has the right OZW status
# Workaround for an incorrect retained OZW status in MQTT
# https://github.com/home-assistant/hassio-addons/issues/1462
mqtt::ensure_ozw_offline_status \
    127.0.0.1 1883 ozw "${MQTT_PASSWORD}" "${OZW_INSTANCE}"

# Send out discovery information to Home Assistant
./discovery &

# Run daemon
cd /data/ozw || bashio::exit.nok "Could not change to OZW working directory"
exec ozwdaemon \
    -s "${OZW_DEVICE}" \
    --config-dir "${OZW_CONFIG}" \
    --user-dir "${OZW_CONFIG}" \
    --mqtt-server 127.0.0.1 \
    --mqtt-port 1883 \
    --mqtt-username ozw \
    --mqtt-instance "${OZW_INSTANCE}" \
    --stop-on-failure
