<?php
/** I'm getting sick of these bad backup solutions using logrotate or others progs not made for that.
So this is a script that takes a pattern that is a file or dir which is backuped every day
This deletes the old backups, leaving just a backup per day for the last week,
a backup pey week for the last month,
and a backup per month.
Backups are renamed with the date.
The backups aren't renamed if their name already contains a date (YYYY-MM-DD)
Salagir Fev 2008 - Apr 2009 - Version 1.1
v1.1: Bugs if the files didn't already have the date in their name
v1.0: Finished Version
*/
// If this is to "true", the script won't affect anything and 'll tell what it would do
define('DEBUG', true);
if (!$argv[1]) {
echo "Usage: php ".basename(__FILE__)." '[pattern]'\n";
echo "Example of pattern : '../../somedir/somefile*gz'\n";
die();
}
if (preg_match('%^[*].*/%', $argv[1])) {
// a * before the last / means all files aren't in the same folder...
echo "I don't trust your pattern.\n";
die();
}
$All = glob($argv[1]);
if (!$All) {
echo "Couldn't find anything with your stupid pattern.\n";
die();
}
if (count($All)>50) {
echo "This pattern must really sucks. Too much files for your own good.\n";
die();
}
///////////////// begin real code /////////////////
$today = floor( time()/86400 );
$files = array();
foreach($All as $f) {
// number of days the file is old
$d = $today - floor( filemtime($f)/86400 );
$files[$f] = $d;
}
arsort($files);
if (DEBUG) print_r($files);
$week = $month = 0;
foreach($files as $f=>$d) {
if ($d<7) { backup($f); continue; } // current week
if ($d<30) { // current month, one per week must survive
if ($week && $week-7<$d) { deleteme($f); continue; }
$week=$d; backup($f); continue;
}
// on the year...
if ($month && $month-30<$d) { deleteme($f); continue; }
$month=$d; backup($f); continue;
}
function deleteme($f) {
if (DEBUG) {
echo "Would remove $f\n";
return;
}
if (is_dir($f)) {
system (" rm -rf $f "); // PORC ! BAD, BAD !
}
else
unlink($f);
}
function backup($f) {
$date = date('Y-m-d', filemtime($f));
if (preg_match("%".$date."[^/]*$%", $f)) {
if (DEBUG) echo "Would do nothing to $f\n";
return;
}
if (DEBUG) {
echo "Would rename $f to {$f}_$date\n";
return;
}
rename($f, $f.'_'.$date);
}
?>