#!/bin/bash
## /usr/bin/voxl-logger-auto
##
## Trigger helper for the voxl-logger-auto service. It sends commands to the
## voxl-logger-auto control pipe so any trigger source (a script, a button, a
## flight event, etc.) can start/stop recording with a single command.
##
## Usage:
##   voxl-logger-auto start [note...]   begin a recording session
##   voxl-logger-auto stop              end the current session
##   voxl-logger-auto status            print whether a session is active
##   voxl-logger-auto arm-trigger {on|off}
##                                      toggle record-on-arm live AND persist it:
##                                      the daemon applies it immediately (no
##                                      restart) and rewrites its config "trigger"
##                                      field so the change survives a reboot

CONTROL_PIPE="${VOXL_LOGGER_AUTO_PIPE:-/run/mpa/voxl-logger-auto/control}"
STATUS_FILE="/run/voxl-logger-auto.status"

send_cmd() {
	if [ ! -p "$CONTROL_PIPE" ]; then
		echo "ERROR: control pipe $CONTROL_PIPE not found." >&2
		echo "       Is the voxl-logger-auto service running?" >&2
		exit 1
	fi
	# write with a timeout in case nothing is reading the control pipe
	if ! timeout 2 bash -c "printf '%s' \"\$1\" > \"$CONTROL_PIPE\"" _ "$1"; then
		echo "ERROR: failed to send '$1' (no reader on control pipe?)" >&2
		exit 1
	fi
}

case "$1" in
	start)
		note="${*:2}"
		if [ -n "$note" ]; then
			send_cmd "start note=$note"
		else
			send_cmd "start"
		fi
		echo "sent: start" ;;
	stop)
		send_cmd "stop"
		echo "sent: stop" ;;
	status)
		send_cmd "status"
		sleep 0.15
		if [ -f "$STATUS_FILE" ]; then
			cat "$STATUS_FILE"
		else
			echo "no status available"
		fi ;;
	arm-trigger)
		case "$2" in
			on|1|armed|enable|enabled)
				send_cmd "arm_trigger 1"
				echo "sent: arm-trigger on (record on arm)" ;;
			off|0|manual|disable|disabled)
				send_cmd "arm_trigger 0"
				echo "sent: arm-trigger off" ;;
			*)
				echo "Usage: voxl-logger-auto arm-trigger {on|off}" >&2
				exit 1 ;;
		esac ;;
	*)
		echo "Usage: voxl-logger-auto {start [note...] | stop | status | arm-trigger {on|off}}" >&2
		exit 1 ;;
esac
