#!/bin/bash

# WildlifeSystems - sensor read
#
# This script provides a standard wrapper for reading sensors in WildlifeSystems,
# and handles inserting the device serial number and timestamp into the JSON response.
#
# 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.

# Return codes
#
# Further information on WildlifeSystems standard reurn codes can be found
# at https://docs.wildlife.systems/return-codes.html
# 0 - Success
# 2 - no arguments provided

if [[ $# -eq 0 ]]; then
  echo "No arguments supplied"
  exit 2
fi

if [[ $1 == "list" ]]; then
  find /usr/bin -name 'sensor-*' -executable | while read SENS_SCRIPT; do
    # Execute the sensor script with a parameter
    $SENS_SCRIPT identify
    if [[ $? -eq 60 ]]; then
      # If the sensor script returns 60, it is a valid sensor script
      SCRIPT=$(basename $SENS_SCRIPT)
      # Remove the "sensor-" prefix
      SCRIPT=${SCRIPT#sensor-}
      echo "$SCRIPT"
    fi
  done
  exit 0
fi
SCRIPT=$1

if [[ $# -eq 2 ]]; then
  DEV=$2
else
  DEV="all"
fi

PI_SERIAL=$(grep Serial /proc/cpuinfo | cut -d ' ' -f 2)
TSTAMP=$(date +%s)

if [[ $SCRIPT == "all" ]]; then
  for SENSOR_SCRIPT in $(sr list); do

    DEV="all"
    SENS_SCRIPT="sensor-$SENSOR_SCRIPT"

    SENS_JSON=$($SENS_SCRIPT ${DEV})

    # If the ineternal object of SENS_JSON is true then exclude it from the output
    if [[ $SCRIPT == "external" && $(echo $SENS_JSON | jq '.internal') == "true" ]]; then
      continue
    fi
    # If the ineternal object of SENS_JSON is false then include it in the output
    if [[ $SCRIPT == "internal" && $(echo $SENS_JSON | jq '.internal') == "false" ]]; then
      continue
    fi

    SENS_JSON=$(echo $SENS_JSON | jq -c ".[].node_id |= \"${PI_SERIAL}\" | .[].timestamp |= ${TSTAMP}")

    # Use jq to merge the arrays ALL_JSON and SENS_JSON
    if [[ -z $ALL_JSON ]]; then
      ALL_JSON=$SENS_JSON
    else
      ALL_JSON=$(echo "$ALL_JSON" "$SENS_JSON" | jq -s 'add')
    fi
  done

  echo $ALL_JSON
  exit 0
fi

if [[ $SCRIPT == "external" ]]; then
  ALL_JSON=$(sr all | jq -c 'del(.[] | select(.internal == true))')
  echo $ALL_JSON
  exit 0
fi

if [[ $SCRIPT == "internal" ]]; then
  ALL_JSON=$(sr all | jq -c 'del(.[] | select(.internal == false))')
  echo $ALL_JSON
  exit 0
fi


SENS_SCRIPT="sensor-$1"

if [[ $DEV == "list" ]]; then
  $SENS_SCRIPT list
  exit 0
fi



SENS_JSON=$($SENS_SCRIPT ${DEV})

# Terminate with error code from sensor script if error thrown
if [[ $? -ne 0 ]]; then
  if [[ $? -eq 20 ]]; then
    echo "Unknown device"
  fi
  if [[ $? -eq 21 ]]; then
    echo "Unknown sensor"
  fi
  exit $?
fi

SENS_JSON=$(echo $SENS_JSON | jq ".[].node_id |= \"${PI_SERIAL}\" | .[].timestamp |= ${TSTAMP}")

echo $SENS_JSON

exit 0
