#!/bin/bash

###
### webcams GROUP
###

UNLIMITED_BUILD=$(jq -r '.unlimited?==true' ${1:-webcams.json})

WEBCAMS=$(jq -r '.[].name' ${1:-webcams.json})

## SENSORS
if [ "${UNLIMITED_BUILD:-null}" != 'true' ]; then
  WEBCAM_SENSORS='annotated_ago annotated_counter annotated_percent detected_ago detected_counter detected_entity_ago detected_entity_counter'
else
  WEBCAM_SENSORS='annotated_percent detected_ago detected_percent detected_entity_ago detected_entity_percent'
fi

echo "###"
echo "## AUTOGENERATED from ${0} ${*}"
echo "## motion/group/webcams.yaml"
echo "###"
echo ""

for WID in ${WEBCAM_SENSORS}; do
  echo "#"
  echo "motion_${WID}:"
  echo "  name: motion_${WID}"
  echo "  entities:"
  for C in ${WEBCAMS}; do
    echo "    - sensor.motion_${C}_${WID}"
  done
done

## BINARY_SENSORS
if [ "${UNLIMITED_BUILD:-null}" != 'true' ]; then
  WEBCAM_BINARY_SENSORS='status_camera end annotated detected detected_entity detect_entity_alert detect_entity_speak'
else
  WEBCAM_BINARY_SENSORS='status_camera detected detected_entity face_detected alpr_detected'
fi

for WID in ${WEBCAM_BINARY_SENSORS}; do
  echo "#"
  echo "motion_${WID}:"
  echo "  name: motion_${WID}"
  echo -n "  all: "
  if [ "${WID}" == 'status_camera' ]; then
    echo "true"
  else
    echo "false"
  fi
  echo "  entities:"
  for C in ${WEBCAMS}; do
    echo "    - binary_sensor.motion_${C}_${WID}"
  done
done

## CAMERAS
if [ "${UNLIMITED_BUILD:-null}" != 'true' ]; then
  WEBCAM_CAMERAS='event_animated live'
else
  WEBCAM_CAMERAS='live'
fi

for WID in ${WEBCAM_CAMERAS}; do
  echo "#"
  echo "motion_${WID}_webcams:"
  echo "  name: motion_${WID}_webcams"
  echo "  entities:"
  for C in ${WEBCAMS}; do
    echo "    - camera.motion_${C}_${WID}"
  done
done
