#!/usr/bin/with-contenv bashio
# ==============================================================================
# Register Home Assistant skill with Almond
# ==============================================================================
declare access_token_expires
declare almond_config

# Wait for Almond service to be available
bashio::net.wait_for 3000

# Calulcate token expire time value
access_token_expires="$((
    $((
        $(date +%s) + 60 * 60 * 24 * 365 * 5
    )) * 1000
)).$(date +%N)"

# Prepare Almond configuration payload
almond_config=$(\
    bashio::var.json \
        kind "io.home-assistant" \
        hassUrl "http://supervisor/core" \
        accessToken "${SUPERVISOR_TOKEN}" \
        refreshToken "" \
        accessTokenExpires "^${access_token_expires}" \
        isHassio "^true" \
)

# Create Home Assistant entry in Almond service
if curl \
    -f -s -X POST -H "Content-Type: application/json" \
    -d "${almond_config}" \
    "http://127.0.0.1:3000/api/devices/create"
then
    bashio::log.info "Successfully register local Home Assistant on Almond"
else
    bashio::log.error "Almond registration of local Home Assistant failed!"
fi
