#!/usr/bin/perl
#
# purge_snapshot.pl
#
# 2014-04-14
#
use File::Basename 'basename', 'dirname';
use File::Path 'rmtree';
# use File::Copy;
use FindBin;
# get script directory
$SDIR = $FindBin::Bin;
# print $SDIR."\n";
require "$SDIR/config.pl";
$return_code = 0;
#
# Get the snapshot directory list.
#
if (!opendir(DIRHANDLE, $SNAPSHOT_DIR)) {
printf(STDERR "%s: Cannot open snapshot directory: %s.\n", $0, $SNAPSHOT_DIR);
exit 1;
}
@dirs;
foreach(readdir(DIRHANDLE)){
# print "$_\n";
next if /^\.{1,2}$/; # skip '.' and '..'
$dir = sprintf("%s/%s", $SNAPSHOT_DIR, $_);
if (! $dir =~ /^\@GMT\-/) { next; } # @GMT-
if (! -d $dir) { next; }
push(@dirs, $dir);
# print "$dir\n";
}
closedir(DIRHANDLE);
@dirs = sort @dirs;
# print join(',',@dirs),"\n";
#
# Keep constant the number of snapshots.
#
$cut = $#dirs - $KEEP_NUMBER_OF_SNAPSHOT + 1;
if ($cut < 1) {
printf("%s: No need to purge.\n", $0);
exit($return_code);
}
# Merge from new snapshots to old,
# put snapshots together to $dst.
for ($i = $cut; $i > 0; $i--) {
$src = sprintf("%s", $dirs[$i]);
$dst = sprintf("%s", $dirs[$i - 1]);
printf("%s: %s => %s\n", $0, $src, $dst);
$cmd = sprintf("%s -av --max-size=%s --exclude-from='%s' '%s/' '%s/'", $RSYNC, $MAX_SIZE, $EXCLUDE_FROM, $src, $dst);
printf("%s: execute: %s\n", $0, $cmd);
if (system($cmd) > 0) {
printf(STDERR "%s: failed to execute: %s\n", $0, $cmd);
$return_code++;
next;
}
rmtree($src);
}
if ($return_code) {
exit($return_code);
}
# Move from the merged snapshot to new.
# from $dst to $dirs[$cut]
# don't use rename and move
$save = sprintf("%s", $dirs[$cut]);
printf("%s: %s => %s\n", $0, $dst, $save);
$cmd = sprintf("%s -av --max-size=%s --exclude-from='%s' '%s/' '%s/'", $RSYNC, $MAX_SIZE, $EXCLUDE_FROM, $dst, $save);
printf("%s: execute: %s\n", $0, $cmd);
if (system($cmd) > 0) {
$return_code++;
printf("%s: failed to execute: %s\n", $0, $cmd);
} else {
rmtree($dst);
}
if ($SNAPSHOT_DIR =~ /snapshot$/ && $DELETE_IF_DAY_AFTER_N_DAYS > 14) {
printf("%s: delete the snapshot files that is %d days old from the changed.\n", $0, $DELETE_IF_DAY_AFTER_N_DAYS);
$files = `$FIND '$SNAPSHOT_DIR' -mtime +$DELETE_IF_DAY_AFTER_N_DAYS -delete -print`;
if ($files) {
printf("%s: deleted old snapshot files: %s\n", $0, $DELETE_IF_DAY_AFTER_N_DAYS, join(", ", $files));
}
# delete empty snapshot directories
$files = `$FIND '$SNAPSHOT_DIR' -type d -empty -delete -print`;
if ($files) {
printf("%s: delete empty snapshot directories: %s\n", $0, join(", ", $files));
}
}
exit($return_code);