#!/bin/bash

# --- CONFIGURATION FROM ENVIRONMENT VARIABLES ---
CLIENT_ID="${FLAIR_CLIENT_ID}"
CLIENT_SECRET="${FLAIR_CLIENT_SECRET}"

if [ -z "$CLIENT_ID" ] || [ -z "$CLIENT_SECRET" ]; then
    echo "Error: Missing environment variables." >&2
    echo "Please set FLAIR_CLIENT_ID and FLAIR_CLIENT_SECRET before running this script." >&2
    exit 1
fi

MQTT_BROKER="192.168.0.6"
MQTT_PORT="1883"
# Matching your requested structure
MQTT_TOPIC_BASE="AstropotaPOD/sensor"

# --- HELPER: GET OAUTH2 TOKEN ---
get_flair_token() {
    local token_response
    token_response=$(curl -s -X POST "https://api.flair.co/oauth2/token" \
        -d "grant_type=client_credentials" \
        -d "client_id=${CLIENT_ID}" \
        -d "client_secret=${CLIENT_SECRET}")
    
    echo "$token_response" | jq -r '.access_token // empty'
}

# --- FETCH REFRESHED TOKEN ---
TOKEN=$(get_flair_token)
if [ -z "$TOKEN" ] || [ "$TOKEN" == "null" ]; then
    echo "Failed to authenticate with Flair." >&2
    exit 1
fi

# --- FETCH AND PUBLISH TO MQTT ---
PAYLOAD=$(curl -s -X GET "https://api.flair.co/api/puck2s" \
    -H "Authorization: Bearer ${TOKEN}" \
    -H "Accept: application/json")

do_pub() {
  mosquitto_pub -h "$MQTT_BROKER" -p "$MQTT_PORT" -t "${TARGET_TOPIC}/${1}" -m "$2" -r
}

while read -r puck_data; do
    if [ -z "$puck_data" ]; then continue; fi

    # Grab the human-readable name from your payload (e.g., "AstropotaPOD-e9af")
    puck_name=$(echo "$puck_data" | jq -r '.attributes.name // empty')
    
    # Fallback to ID just in case a device doesn't have a custom name assigned
    if [ -z "$puck_name" ] || [ "$puck_name" == "null" ]; then
        puck_name=$(echo "$puck_data" | jq -r '.id')
    fi

    # Extract metrics from payload attributes
    temp_c=$(echo "$puck_data" | jq -r '.attributes."current-temperature-c" // empty')
    humidity=$(echo "$puck_data" | jq -r '.attributes."current-humidity" // empty')
    wifi_rssi=$(echo "$puck_data" | jq -r '.attributes."current-wifi-rssi" // empty')
    power_source=$(echo "$puck_data" | jq -r '.attributes."power-source" // empty')
    
    reporting_interval=$(echo "$puck_data" | jq -r '.attributes."reporting-interval-ds" // empty')
    firmware=$(echo "$puck_data" | jq -r '.attributes."firmware-version" // empty')
    beacon_ms=$(echo "$puck_data" | jq -r '.attributes."beacon-interval-ms" // empty')

    voltage=$(echo "$puck_data" | jq -r '.attributes.voltage')
    last_voltage=$(echo "$puck_data" | jq -r '.attributes."last-reported-voltage"')
    if [ "$voltage" == "0" ] || [ "$voltage" == "0.0" ]; then
        battery="$last_voltage"
    else
        battery="$voltage"
    fi

    # Dynamic target base matching your requested pattern: AstropotaPOD/sensor/AstropotaPOD-e9af/
    TARGET_TOPIC="${MQTT_TOPIC_BASE}/${puck_name}"

    # Blast sub-topics cleanly to Mosquitto
    [ -n "$temp_c" ] && do_pub "temperature" "$temp_c"
    [ -n "$humidity" ] && do_pub "humidity" "$humidity"
    [ -n "$wifi_rssi" ] && do_pub "wifi_rssi" "$wifi_rssi"
    [ -n "$power_source" ] && do_pub "power_source" "$power_source"
    [ -n "$battery" ] && do_pub "battery_voltage" "$battery"
    [ -n "$reporting_interval" ] && do_pub "reporting_interval" "$reporting_interval"
    [ -n "$firmware" ] && do_pub "firmware_version" "$firmware"
    [ -n "$beacon_ms" ] && do_pub "beacon_interval" "$beacon_ms"

#    echo "Published to MQTT under: ${TARGET_TOPIC}/"

done < <(echo "$PAYLOAD" | jq -c '.data[]')
