<?php

class cronjob_nh_logrotate extends cronjob {

	// job schedule
	protected $_schedule = '58 23 * * *';
	protected $_run_at_new = true;

	private $_tools = null;

        /* this function is optional if it contains no custom code */
        public function onPrepare() {
                global $app;

                parent::onPrepare();
        }

        /* this function is optional if it contains no custom code */
        public function onBeforeRun() {
                global $app;

                return parent::onBeforeRun();
        }

	public function onRunJob() {
		global $app, $conf;

	        function nhLogrotate($filename) {
	                global $conf, $app;

        	        $num_map = array();

	                foreach (scandir($conf['ispconfig_log_dir']) as $fInfo) {
	                        if($fInfo != ".." && $fInfo != ".") {

	                                if (preg_match('/'.$filename.'\.?([0-9]*)\.gz$/', $fInfo, $matches) ) {
	                                        $num = $matches[1];
	                                        $file2move = $fInfo;
	                                        if ($num == '') $num = -1;
	                                        $num_map[$num] = $file2move;
	                                }
	                        }
	                }

	                krsort($num_map);
	                foreach ($num_map as $num => $file2move) {
	                        $targetN = $num+1;

	                        if ($num >= 15) {
	                                exec('rm -r '.$conf['ispconfig_log_dir'].'/'.$file2move);
	                        } else {
	                                rename($conf['ispconfig_log_dir']."/".$file2move,$conf['ispconfig_log_dir']."/".$filename.".".$targetN.".gz");
	                        }
        	        }
	        }

		$logfile = $conf['ispconfig_log_dir'].'/ispconfig.log';
                if(is_file($logfile) && filesize($logfile) > 10000000) {
			nhLogrotate('ispconfig.log');
		}
		unset($logfile);

		$logfile = $conf['ispconfig_log_dir'].'/cron.log';
                if(is_file($logfile) && filesize($logfile) > 10000000) {
			nhLogrotate('cron.log');
		}
		unset($logfile);

		$logfile = $conf['ispconfig_log_dir'].'/auth.log';
                if(is_file($logfile) && filesize($logfile) > 10000000) {
			nhLogrotate('auth.log');
		}

		parent::onRunJob();
	}


        /* this function is optional if it contains no custom code */
        public function onAfterRun() {
                global $app;

                parent::onAfterRun();
        }

}

?>
