#!/bin/bash

dates=
months=
years=

for bd in "/srv/unifi-video/videos" "/srv/unifi-video/thumbnails"
do
  echo "search in $bd"
  for i in {0..31}
  do
    dt=`/bin/date -d "-$i days" +%Y%m%d`
    year=`/bin/date -d "-$i days" +%Y`
    mon=`/bin/date -d "-$i days" +%m`
    day=`/bin/date -d "-$i days" +%d`
  # echo "skiping date "$dt
    dates+=" $year/$mon/$day"
    if [[ ! $months =~ (^|[[:space:]])$year/$mon($|[[:space:]]) ]]; then
      months+=" $year/$mon"
    fi
    if [[ ! $years =~ (^|[[:space:]])$year($|[[:space:]]) ]]; then
      years+=" $year"
    fi
  done

  for bd_l1 in `ls $bd`; do
    echo $bd_l1
    for bd_l2 in `ls $bd/$bd_l1`; do
      echo -n "   "$bd_l2

      if [[ ! $years =~ (^|[[:space:]])$bd_l2($|[[:space:]]) ]]; then
        echo "... must remove $bd/$bd_l1/$bd_l2"
        rm -rf "$bd/$bd_l1/$bd_l2"
           #&& rmdir "$bd/$bd_l1/$bd_l2"
      else
        echo
        for bd_l3 in `ls $bd/$bd_l1/$bd_l2`; do
          echo -n "      "$bd_l3
          if [[ ! $months =~ (^|[[:space:]])$bd_l2/$bd_l3($|[[:space:]]) ]]; then
            echo "... must remove $bd/$bd_l1/$bd_l2/$bd_l3"
            rm -rf "$bd/$bd_l1/$bd_l2/$bd_l3"
               #&& rmdir "$bd/$bd_l1/$bd_l2/$bd_l3"
          else
            echo
            for bd_l4 in `ls $bd/$bd_l1/$bd_l2/$bd_l3`; do
              echo -n "         "$bd_l4
              if [[ ! $dates =~ (^|[[:space:]])$bd_l2/$bd_l3/$bd_l4($|[[:space:]]) ]]; then
                echo " ... must remove $bd/$bd_l1/$bd_l2/$bd_l3/$bd_l4"
                rm -rf "$bd/$bd_l1/$bd_l2/$bd_l3/$bd_l4"
                   #&& rmdir "$bd/$bd_l1/$bd_l2/$bd_l3/$bd_l4"
              else
                echo
              fi
            done
          fi
        done
      fi
    done
    echo
  done
done
