<?php
$logDirectory='/var/log/icebear/';
$logFilesToKeep=7;

if(!file_exists($logDirectory)){
    die("Log directory $logDirectory does not exist.");
}
if(!is_int($logFilesToKeep) || $logFilesToKeep<1){
    die("Log files to keep: Must be a positive integer.");
}

$logs=[];
$files=scandir($logDirectory);
foreach($files as $file){
    $parts=explode('.log', $file);
    $log=$parts[0];
    if($log===$file){ continue; }
    if(in_array($log, $logs)){ continue; }
    $logs[]=$log;
    $log=rtrim($logDirectory,'/')."/$log.log";
    for($i=$logFilesToKeep;$i>=1;$i--){
        if(file_exists($log.'.'.($i-1)) && !@rename($log.'.'.($i-1), $log.'.'.$i)){
            echo 'Could not rotate log file '.$log.'.'.($i-1).' to '.$log.'.'.$i;
        }
    }
    if(file_exists($log) && !@rename($log, $log.'.1')){
        echo "Could not rotate log file $log to $log.1\n";
    }
}
