#!/bin/sh
. /usr/nvr/nvrcommon

function main() {
	test_totaldays
	test_loopwrite
	for a in $_all_clients;do
		theday="$(date +%Y-%m-%d)"
		thedir=$(echo $a | sed 's/\///g')
		if [ ! -d "$_directory/$theday/$thedir" ];then
			mkdir -p "$_directory/$theday/$thedir"
		fi
		if [ "$_source" = "hikvision" ];then
			_input="rtsp://${_hik_user}:${_hik_pass}@${a}:554/h264/ch1/main/av_stream"
		elif [ "$_source" = "tplink" ];then
			_input="rtsp://${_tplink_user}:${_tplink_pass}@${a}:554/stream1"
		elif [ "$_source" = "rtmp-url" ];then
			_input="$a"
		elif [ "$_source" = "multiple-types" ];then
			_input="$a"
		fi
		if [ ! -f "${_directory}/${theday}/${thedir}/${thename}.*" ];then
			kill -9 "$(ps -w | grep ffmpeg | grep "${_input}" | grep -v grep | grep -v "\-f flv")"
		fi
		thename="$(date +%Y-%m-%d-%H:%M:%S)"
		if [ "$_enable_audio" -eq 1 ];then
			ffmpeg -i "${_input}" -c copy -t ${_rec_time} "${_directory}/${theday}/${thedir}/${thename}.mkv" &
		else
			ffmpeg -i "${_input}" -vcodec copy -an -t ${_rec_time} "${_directory}/${theday}/${thedir}/${thename}.mp4" &
		fi
	done
	sleep $(expr ${_rec_time} - 6)
}

while true;do
	detect_disk
	if [ "${_disk}" = "" ];then
		main
	else
		sleep 10
	fi
done
