#!/usr/bin/with-contenv bashio
# ==============================================================================
# Start deCONZ service
# ==============================================================================
TMP_FOLDER=$(mktemp -d)

# Lookup udev link
DECONZ_DEVICE=$(bashio::config 'device')

# VNC is not enabled as a separate service, as it cannot handle multiple
# session when running in the foreground.
VNC_PORT="$(bashio::addon.port 5900)"
ARCH="$(bashio::info.arch)"

# Fix tigervnc for 32 bits ARM
if [[ "armhf armv7" = *"${ARCH}"* ]]; then
    export LD_PRELOAD=/lib/arm-linux-gnueabihf/libgcc_s.so.1
fi

# Fix tigervnc for 64 bits ARM
if [[ "aarch64" = "${ARCH}" ]]; then
    export LD_PRELOAD=/lib/aarch64-linux-gnu/libgcc_s.so.1
fi

# Run it only on localhost if not expose
if bashio::var.has_value "${VNC_PORT}"; then
    bashio::log.warning "Your direct VNC access is not protected!"
    LOCAL_ONLY=no
else
    LOCAL_ONLY=yes
fi

export XDG_RUNTIME_DIR="${TMP_FOLDER}"
export DISPLAY=":0"

bashio::log.info "Starting VNC server (local/${LOCAL_ONLY})..."
tigervncserver \
    -name "Home Assistant - deCONZ" \
    -geometry 1920x1080 \
    -depth 16 \
    -localhost ${LOCAL_ONLY} \
    -SecurityTypes None \
    --I-KNOW-THIS-IS-INSECURE \
    "${DISPLAY}" \
    &> /dev/null

# Wait for VNC server to start before continuing
bashio::log.info "deCONZ waiting for VNC to start"
bashio::net.wait_for 5900

# Load debug values
bashio::config.has_value 'dbg_info' \
    && DBG_INFO="$(bashio::config 'dbg_info')" || DBG_INFO=1
bashio::config.has_value 'dbg_aps' \
    && DBG_APS="$(bashio::config 'dbg_aps')" || DBG_APS=0
bashio::config.has_value 'dbg_otau' \
    && DBG_OTAU="$(bashio::config 'dbg_otau')" || DBG_OTAU=0
bashio::config.has_value 'dbg_zcl' \
    && DBG_ZCL="$(bashio::config 'dbg_zcl')" || DBG_ZCL=0
bashio::config.has_value 'dbg_zdp' \
    && DBG_ZDP="$(bashio::config 'dbg_zdp')" || DBG_ZDP=0

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

# Start deCONZ
bashio::log.info "Starting the deCONZ gateway..."
exec deCONZ \
    -platform "xcb" \
    --auto-connect=1 \
    --dbg-info="${DBG_INFO}" \
    --dbg-aps="${DBG_APS}" \
    --dbg-otau="${DBG_OTAU}" \
    --dbg-zcl="${DBG_ZCL}" \
    --dbg-zdp="${DBG_ZDP}" \
    --upnp=0 \
    --http-port=40850 \
    --ws-port=8081 \
    --dev="${DECONZ_DEVICE}"
