<?php


function findFiles($dir = '.', $pattern = '/./'){
  $prefix = $dir . '/';
  $dir = dir($dir);
  while (false !== ($file = $dir->read())){
    if ($file === '.' || $file === '..') continue;
    $file = $prefix . $file;
    if (is_dir($file)) findFiles($file, $pattern);
    if (preg_match($pattern, $file)){
        $result = shell_exec('grep RRULE\:FREQ=WEEKLY ' . $file . ' | uniq -dc');
        if($result != '')
        {
                echo "Fixing " . $file . "\n";
                $originalPath = pathinfo($file);
                $backupPath = '/root/backup-calendar/fixics/' .  trim($originalPath['dirname'], './');
                @mkdir( $backupPath, 0740, true);
                $filecounter = 0;
                $filename = $backupPath . '/' . $originalPath['basename'];
                while(is_file($filename))
                {
                        $filecounter ++;
                        $filename = $backupPath . '/' . $originalPath['basename'] . '.' . $filecounter;
                }
                // make a backup
                shell_exec('cp ' . $file . ' ' . $filename);
                // fix rrule dups
                shell_exec('cat ' . $filename . " | awk 'a !~ $0; {a=$0}' > " . $file);
        }
    }
  }
}
findFiles('.', '/\.ics$/');
