#! /bin/bash
disabled="false"
threshold="0.040"
vdir=/tmp/tmpfs
exec > >(tee "$vdir/backup.log") 2>&1
if ! [ -d "$vdir" ]; then
   echo $vdir does not exist >&2
   exit 1
fi
if ps aux | \
   grep -v grep | \
   grep -E 'services.backups.rclone|local.ffprobe'; then
   echo skipping colliding run >&2
   exit 0
fi
echo ok at 1
files=($(find $vdir -type f -name "*.m*"))
if [ "${#files[@]}" == "0" ]; then
   echo no files found >&2
   exit 0
fi
echo files=${files[@]}
includes=()
printf "reviewing"; printf "   %s\n" "${files[@]}"
echo ok at 2
for file in "${files[@]}"; do
   frames="$(
	  nice -n 19 /var/services/homes/squeaky2x3/ffmpeg-local/ffprobe \
      -threads 1 -loglevel error -hide_banner -show_frames -of compact=p=0 \
      -f lavfi "movie=$file,select=gt(scene\\,$threshold)" 2> /dev/null \
   )"
   ret=$?
   if [ $ret -eq 0 ] && [ $(printf "%s\n" "$frames" | wc -l) -lt 2 ]; then
      echo file has no movement $file >&2
      rm -f "$file"
   elif [ $ret -ne 0 ]; then
      echo failed scanning $file >&2
      files=("${files[@]/"$file"}")
   else
      echo file has movement $file
      includes+=("$(basename "$file")")
   fi
done
echo "pushing files ${includes[@]}"
if [ "${#includes[@]}" -gt 0 ]; then
   if [ "$disabled" == "true" ] || \
      /volume1/homes/squeaky2x3/services/backups/rclone \
      --config /volume1/homes/squeaky2x3/services/backups/rclone.conf \
      copy \
      $vdir/ \
      blapointe-drive:/projects/cctv/ut/ \
      $(printf " --include %s" "${includes[@]}") ; then
      rm -f "${files[@]}"
   fi
fi
echo donezo
echo why
