#!/bin/bash

# WildlifeSystems
#
# 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 return codes can be found
# at https://docs.wildlife.systems/return-codes.html
# 0 - Success
# 10 - invalid argument

if [[ -z "$1" ]]; then
  echo "Error: No argument provided."
  exit 10
fi

# If this script is already running, then wait for exising to finish
while [[ $(pgrep -f ws-indicate | grep -v $$ | wc -l) -gt 1 ]]; do
  # If there are lots of indictions queued, then exit
  if [[ $(pgrep -f ws-indicate | grep -v $$ | wc -l) -gt 10 ]]; then
    exit 1
  fi
  sleep 0.1
done

#Initial state
if [ -d /sys/class/leds/led0 ]; then
	ATINIT=$(awk -F'[][]' '{print $2}' /sys/class/leds/led0/trigger)
	ABINIT=$(cat /sys/class/leds/led0/brightness)
else
  if [ -d /sys/class/leds/ACT ]; then
	ATINIT=$(awk -F'[][]' '{print $2}' /sys/class/leds/ACT/trigger)
	ABINIT=$(cat /sys/class/leds/ACT/brightness)
  fi
fi

MODEL=$(pi-data model)

if [[ "$MODEL" != "000d" ]]; then
  if [ -d /sys/class/leds/led1 ]; then
	PTINIT=$(awk -F'[][]' '{print $2}' /sys/class/leds/led1/trigger)
	PBINIT=$(cat /sys/class/leds/led1/brightness)
  else
	if [ -d /sys/class/leds/PWR ]; then
	  PTINIT=$(awk -F'[][]' '{print $2}' /sys/class/leds/PWR/trigger)
	  PBINIT=$(cat /sys/class/leds/PWR/brightness)
	fi
  fi
fi

#Indicators
case "$1" in
	list)
		echo "$ATINIT"
		echo "$ABINIT"
		echo "$PTINIT"
		echo "$PBINIT"
		exit 0
		;;

	heartbeat)
		for _ in {1..2}; do
			pi-pwr on actled &
			pi-pwr off pwrled &
			sleep 0.1
			pi-pwr on pwrled &
			pi-pwr off actled &
			sleep 0.1
		done
		;;

	countdown)
		if [[ -z "$2" || ! "$2" =~ ^[0-9]+$ ]]; then
			echo "Error: Countdown requires a numeric argument."
			exit 10
		fi
		pi-pwr off actled &
		for i in $(seq "$2" -1 0); do
			pi-pwr off pwrled &
			sleep 0.5
			pi-pwr on pwrled &
			sleep 0.5
			echo "$i"
		done
		;;

	record)
		pi-pwr off actled &
		pi-pwr on pwrled &
		$2
		pi-pwr off pwrled &
		;;

	*)
		exit 10
esac

#Restore initial state
if [ -d /sys/class/leds/led0 ]; then
  echo "$ABINIT" | sudo tee /sys/class/leds/led0/brightness >> /dev/null
  echo "$ATINIT" | sudo tee /sys/class/leds/led0/trigger >> /dev/null
else
  if [ -d /sys/class/leds/ACT ]; then
	echo "$ABINIT" | sudo tee /sys/class/leds/ACT/brightness >> /dev/null
	echo "$ATINIT" | sudo tee /sys/class/leds/ACT/trigger >> /dev/null
  fi
fi


if [[ "$MODEL" != "000d" ]]; then
  if [ -d /sys/class/leds/led1 ]; then
	echo "$PBINIT" | sudo tee /sys/class/leds/led1/brightness >> /dev/null
	echo "$PTINIT" | sudo tee /sys/class/leds/led1/trigger >> /dev/null
  else
	if [ -d /sys/class/leds/PWR ]; then
	  echo "$PBINIT" | sudo tee /sys/class/leds/PWR/brightness >> /dev/null
	  echo "$PTINIT" | sudo tee /sys/class/leds/PWR/trigger >> /dev/null
	fi
  fi
fi
