#!/bin/sh

set -e

FFMPEG=`which ffmpeg 2>/dev/null || echo ""`
FFPROBE=`which ffprobe 2>/dev/null || echo ""`
FILE=$1

if test -z "$FFMPEG"; then
  echo "ffmpeg must be installed"
  exit 1
fi

SED=`which gsed 2>/dev/null || echo ""`

if test -z "$SED"; then
  SED=`which sed 2>/dev/null || echo ""`
fi

if test -z "$SED"; then
  echo "sed or gsed must be installed"
  exit 1
fi

# check for replaygain metadata
if [ -n "$FFPROBE" ]; then
  RG=`$FFPROBE "$FILE" 2>&1 | $SED -n -r 's/.* REPLAYGAIN_TRACK_GAIN: ([-+]?[0-9]+\.[0-9]+ dB).*/\1/pi'`

  if [ -n "$RG" ]; then
    echo "$RG"
    exit 0
  fi
fi

# no replaygain metadata: compute it
$FFMPEG -i "$FILE" -vn -filter replaygain -f null /dev/null 2>&1 | $SED -n -r 's/.* track_gain = ([-+]?[0-9]+\.[0-9]+ dB).*/\1/p'
