#!/bin/bash

#
#  Copyright 2007, DevZuz Inc.
#
#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.
#

######
# Who:
#	Aimon Bustardo <me@aimon.net>
# What:
# 	Continuum Snapshot Cleaner v0.1.3
# When:
# 	10/29/2007
# Where:
#	DevZuz Inc.
# Why:
#	'cause nobody else had.
# ToDo:
#	- Add regex checking to be sure we are actually processing a maestro snapshots dir
#	- Add report on what was deleted.. maybe with a -v option
#	- Add support for preserving files longer than 1 month
#
# Changes:
#	- Added check to make sure arguments are valid
#	
######



usage="usage: $0 <snapshot path> <preserve days>"
if [[ -z $1 || -z $2 ]]
then
        echo $usage;
        exit 1;
fi
if [[ -z `echo $2 |grep -e "^[1-9]$" -e "^[1-3][0-9]$"` ]]
then
	echo "Second argument is not a valid number."
	exit 1;
fi
if [[ -z `echo $1 |grep -E "(/[a-zA-Z0-9._-]{1,128}){1,32}-SNAPSHOT"` ]]
then
	echo "First argument is not a valid SNAPSHOT dir.";
	exit 1;
fi


#Build file prefix
prefix=`echo $1 |awk 'BEGIN{FS="/";}{file=$(NF-1)"-"$NF; sub("-SNAPSHOT", "", file); print file;}'`



ls $1 |grep $prefix |sort -i |  
awk --re-interval -v path=$1 -v preserve=$2 '
BEGIN{
        td=strftime("%Y%m%d");
        yr=strftime("%Y");
        mo=strftime("%m");
        dy=strftime("%d");

#Days In Month
	dim[1]=31;
	dim[2]=28;
	dim[3]=31;
	dim[4]=30;
	dim[5]=31;
	dim[6]=30;
	dim[7]=31;
	dim[8]=31;
	dim[9]=30;
	dim[10]=31;
	dim[11]=30;
	dim[12]=31;

#Leap Year
	if(yr % 4 == 0){
		dim[2]=29;
	}
	if(preserve>dim[int(mo)]){
        	print "You cannot preserve files older than 1 month.";
        	exit 1;
	}
}
{
        if(dy<=preserve && preserve<=dim[int(mo)]){
                mo=mo-1;
		if(mo==0){
			mo=12;
			yr=yr-1;
		}
                if(yr<10){
                        yr="0"yr
                }
                if(mo<10){
                        mo="0"mo
                }
                dy=dy+dim[mo-1]-preserve;
                if(dy<10){
                        dy="0"dy
                }
        }
        indx=match($0, /20[0-9]{2}(0[1-9]{1}|1[0-2]{1})([0-2]{1}[0-9]{1}|3[0-1]{1}).[0-9]{6}-[0-9]{1,4}/);
        if(indx>0){
                stmp=substr($0, indx, 8)
                if(stmp < (td-preserve)){
                        system("rm -f "path"/"$0);
                }
        }
}'
