#!/usr/bin/with-contenv bashio
# ==============================================================================
# Send deCONZ discovery information to Home Assistant
# ==============================================================================
readonly DATA_STORE="/data/.local/share/dresden-elektronik/deCONZ/zll.db"
declare api_key
declare config
declare query
declare retries
declare serial

# Wait for deCONZ to start before continuing
bashio::net.wait_for 40850

# Remove old discovery data storage (cleanup)
# We now query the deCONZ database for it directly.
if bashio::fs.file_exists /data/hassio.json; then
    rm /data/hassio.json
fi

# Try to get API key from deCONZ database
query='SELECT apikey FROM auth WHERE devicetype="Home Assistant" ORDER BY createdate DESC LIMIT 1'
api_key=$(sqlite3 "${DATA_STORE}" "${query}" .exit)
if ! bashio::var.has_value "${api_key}"; then
    # Register an API key for Home Assistant
    if ! result="$(curl --silent --show-error --request POST -d '{"devicetype": "Home Assistant"}' "http://127.0.0.1:40850/api")";
    then
        bashio::log.debug "${result}"
        bashio::exit.nok "Can't get API key from deCONZ gateway"
    fi
    api_key="$(bashio::jq "${result}" '.[0].success.username')"
fi

# Try to get the bridge ID/serial, try to avoid using 0000000000000000
retries=25
serial="0000000000000000"
while [[ "${serial}" = "0000000000000000" ]]; do
    bashio::log.debug "Waiting for bridge ID..."
    sleep 10

    # If we tried 25 times, just abort.
    if [[ "${retries}" -eq 0 ]]; then
        bashio::exit.nok "Failed to get a valid bridge ID. Discovery aborted."
    fi

    # Get bridge ID from API
    if ! result="$(curl --silent --show-error --request GET "http://127.0.0.1:40850/api/${api_key}/config")";
    then
        bashio::log.debug "${result}"
        bashio::exit.nok "Can't get data from deCONZ gateway"
    fi
    serial="$(bashio::jq "${result}" '.bridgeid')"

    ((retries--))
done

# Create config payload for Home Assistant
config=$(bashio::var.json \
    host "$(hostname)" \
    port "^40850" \
    api_key "${api_key}" \
    serial "${serial}" \
)

# Send discovery info
if bashio::discovery "deconz" "${config}" > /dev/null; then
    bashio::log.info "Successfully send discovery information to Home Assistant."
else
    bashio::log.error "Discovery message to Home Assistant failed!"
fi
