#!/bin/bash

# move last backup to special path
autopath="/var/lib/automysqlbackup"
datepath=$(date '+%F')

if [ -d "$autopath/latest" ]; then
	mv "$autopath/latest" "$autopath/bydate/$datepath"
fi


# cleanup
PATH_CLEAN="$autopath/bydate"

if [ ! -d "$PATH_CLEAN" ]; then
  echo "Path is not a directory" >&2
  exit 1
fi


FILES=$(find "$PATH_CLEAN" -type d)


# check for correct format
FILES=$(echo "$FILES" | egrep ".+[0-9]{4}-[0-9]{2}-[0-9]{2}")


# don't remove last month
for i in `seq 0 30`;
do
	thisMonth=$(date --date="$i days ago" "+%Y-%m-%d")
   	FILES=$(echo "$FILES" | egrep -v ".+$thisMonth")
done

# don't remove first day of month of the last year
for i in `seq 1 12`;
do
	lastMonth=$(date --date="$i months ago" "+%Y-%m-01")
      	FILES=$(echo "$FILES" | egrep -v ".+$lastMonth")
done

# don't remove first day of year (last 5 years)
for i in `seq 1 5`;
do
	lastYear=$(date --date="$i years ago" "+%Y-01-01")
      	FILES=$(echo "$FILES" | egrep -v ".+$lastYear")
done

for file in ${FILES[@]};
do
	#echo "$file"
	rm -rf "$file"
done
