#!/bin/bash

#defaults
instance="$(hostname)"
remote='https://push.radiomon.degenerazione.xyz'
freq=87900000
station=ror
user=
password=

# override defaults with sonda.conf
# important: set $user and $password (to push metrics)
conffile="$(dirname "$0")/sonda.conf"
test -f "$conffile" && source "$conffile"

auth="-u ${user}:${password}"
curl="curl $auth"
snrduration=10

shortfreq=$(bc <<< "scale=1; $freq/1000000")

mkdir -p "/tmp/samples/$station"


export AUDIODEV=default:CARD=SB

timeout $snrduration sox -q -c 1 -t alsa -d -t ogg - | sponge "/tmp/samples/${station}.ogg"
	sox /tmp/samples/$station.ogg -n stats 2>&1 |
	grep -vw -e Bit-depth -e NaN | grep -E '[0-9]$' |
	sed -e 's/\([^ ]\)  *\([-0-9]\)/\1=\2/;s/  */ /;s/^/radio_sox_/'| \
	tr ' ' _|tr -d '():' | \
	tr = ' ' | \
	$curl --data-binary @- "$remote/metrics/job/radio/instance/$instance/freq/$shortfreq/modulation/fm/station/$station"

cp "/tmp/samples/${station}.ogg" "/tmp/samples/$station/$(date '+%F_%T').ogg"

find /tmp/samples/ -mtime +2 -delete
