#!/bin/bash

# WildlifeSystems - read DS18B20 1-Wire temperature sensors.
#
# This script is part of the WildlifeSystems project. For further information
# please refer to https://docs.wildlife.systems, or for more information on
# the project itself, please refer to https://wildlife.systems.

# Check for required commands
if ! command -v jq &> /dev/null; then
    echo "Error: jq is not installed. Please install it with: sudo apt-get install jq" >&2
    exit 1
fi

if ! command -v sc-prototype &> /dev/null; then
    echo "Error: sc-prototype is not installed. Please install sensor-control package." >&2
    exit 1
fi

if [[ "$#" -eq 1 ]]; then
  if [[ "$1"  = "identify" ]]; then
    exit 60;
  fi
  if [[ "$1" == "list" ]]; then
    echo "temperature"
    exit 0
  fi
fi


OUTPUT_COUNT=0

echo -n "["

for folder in /sys/bus/w1/devices/28-*/; do
  if [[ ! -d "$folder" ]]; then
    # Not a directory
    break
  fi

  # Extract sensor ID from folder name
  SENSOR_ID=$(basename "$folder")

  # Read temperature value from w1_slave file
  if [[ -f "$folder/w1_slave" ]]; then
    TEMP=$(awk -F"=" '/t=/ {print $2/1000}' "$folder/w1_slave")
    if [[ -z "$TEMP" || ! "$TEMP" =~ ^-?[0-9]+(\.[0-9]+)?$ ]]; then
      echo "Error: Invalid temperature value in $folder/w1_slave" >&2
      continue
    fi
  else
    echo "Error: Missing w1_slave file in $folder" >&2
    continue
  fi

  # Add a comma if this is not the first sensor
  if [[ $OUTPUT_COUNT -gt 0 ]]; then
    echo -n ","
  fi

  JSON=$(sc-prototype)
  SENSOR=$(echo $JSON | jq ".sensor |= \"ds18b20\" | .measures |= \"temperature\" | .unit |= \"Celsius\"| .value |= ${TEMP} | .sensor_id |= \"${SENSOR_ID}\"")
  echo -n $SENSOR
  OUTPUT_COUNT=$((OUTPUT_COUNT+1))
done

echo "]"

# Warn if no sensors were found
if [[ $OUTPUT_COUNT -eq 0 ]]; then
  echo "Warning: No DS18B20 sensors detected. Please check your wiring and ensure 1-Wire is enabled." >&2
fi
