#!/bin/bash

export LD_LIBRARY_PATH="/usr/local/monitoring/lib"

rtmpdump="/usr/local/monitoring/bin/rtmpdump"

#LD_LIBRARY_PATH=/usr/local/monitoring/lib rtmpdump -r 'rtmp://1_i3gqmr0f.b.kpublish.kaltura.com:1935/kLive/1_i3gqmr0f_1' -A 1 -B 2 -a 'kLive?t=1c1c505' >/dev/null

#(c) 2010 Andrej Stepanchuk, Howard Chu, The Flvstreamer Team; license: GPL
#WARNING: You haven't specified an output file (-o filename), using stdout
#Connecting ...
#INFO: Connected...
#Starting download at: 0.000 kB
#For duration: 1.000 sec
#INFO: Metadata:
#INFO:   presetname            Custom
#INFO:   creationdate          Wed Oct 03 12:54:27 2018
#INFO:   videodevice           Osprey-460e Video Device 2B
#INFO:   framerate             30.00
#INFO:   width                 640.00
#INFO:   height                360.00
#INFO:   videocodecid          avc1
#INFO:   videodatarate         3000.00
#INFO:   avclevel              31.00
#INFO:   avcprofile            77.00
#INFO:   videokeyframe_frequency5.00
#INFO:   audiodevice           Osprey-460e Audio 2B Unbalanced (4- Osprey-460e Capture Device)
#INFO:   audiosamplerate       44100.00
#INFO:   audiochannels         2.00
#INFO:   audioinputvolume      75.00
#INFO:   audiocodecid          .mp3
#INFO:   audiodatarate         128.00
#74.255 kB / 2.02 sec
#Download complete


if [[ "$#" -lt "1" ]]; then
	echo "Usage: $0 <rtmp://URL> [token_key=token]"
	exit 3
fi

tmpfil=/tmp/`basename $0`.$$

url="$1"
app=""

if [[ "$#" -gt "1" ]]; then
	app=`echo "$url" | sed 's|^.*://[^/]\+/||; s|/.*||'`
	app="-a ${app}?$2"
fi

$rtmpdump -r "$url" -A 1 -B 16 $app >/dev/null 2>$tmpfil

stat=$?

cat $tmpfil | grep -q "^INFO: Connected"
if [[ "$?" -eq "0" ]]; then
	cat $tmpfil | grep -q "^Download \(may be in\|\)complete"

	if [[ "$?" -eq "0" ]]; then
		sed -n 's|.*\r\(.*\) / \(.*\)|SUCCESS: Retrieved \1 in \2|p' $tmpfil
		rm -f $tmpfil
		exit 0
	fi
fi

cat $tmpfil
rm -f $tmpfil

exit 2
