#! /bin/bash

echo to start: ${@:-83}

for i in "${@:-83}"; do
   echo starting $i... 
   (
      while true; do
         ffmpeg \
            -threads 0 \
            -nostdin \
            -nostats \
            -loglevel error \
            -i rtsp://192.168.0.$i:8554/unicast \
            -an \
            -map 0 \
            -force_key_frames "expr:gte(t,n_forced*9)" \
            -f segment \
            -segment_time ${SEG:-10} \
            -segment_format mp4 \
            -strftime 1 \
            -minrate .05k \
            -vcodec copy \
            "/tmp/ffmpeg_cap/ffmpeg_capture-$i-%Y%m%d_%H%M%S.mp4" \
            -vf "select=gt(scene\,0.003),setpts=N/(15*TB)" \
            < /dev/null \
            >> ./ffmpegs.log \
            2>&1 
         sleep 30
      done
   ) &
done 

clean() {
   kill -9 $(jobs -p)
}
trap clean EXIT ERR

for i in "${@:-83}"; do
   if ! wait -n 1; then
      echo "Something died" >&2
      exit 1
   fi
   exit 0
done
