<?php
$backupsToKeep=3;
$logDirectory='/var/log/icebear/';
$logFile=$logDirectory.'backup.log';

$bears=[];
$ignored=['vhtest1','icebear-vhtest2'];
$dirs=scandir('/var/www');
foreach($dirs as $dir){
    if(0===stripos($dir,'icebear-')){
        $bears[]=substr($dir,8);
    }
}


if(empty($bears)){
    die('No icebear-* directories in /var/www/ - nothing to back up.\n');
}

foreach($bears as $bear){
    $classes="/var/www/icebear-$bear/classes";
    if(file_exists($classes)){
        include_once("$classes/core/Log.class.php");
        include_once("$classes/core/exception/ServerException.class.php");
        break;
    }
}

if(!file_exists($logDirectory) && !@mkdir($logDirectory)){
    die("Log directory $logDirectory does not exist and could not be created.");
}

Log::init(Log::LOGLEVEL_DEBUG, $logFile);
Log::info('Beginning backup');
Log::info('To back up: '.implode(', ', $bears));

$failed=[];
$succeeded=[];
Log::info('----------------------------------');
foreach($bears as $bear){
    if(in_array($bear, $ignored) || in_array("icebear-$bear",$ignored)){
        Log::warning("$bear is in the ignore list. Not backing it up.");
        Log::info('----------------------------------');
        continue;
    }

    Log::info("Backing up icebear-$bear");
    try{
        $backupDir="/mnt/icebearstore-$bear/dbbackups/";
        $wwwRoot="/var/www/icebear-$bear/";
        $dbName="icebear_$bear";
        $sqlFilename="icebear-$bear.sql";
        $tarFilename="icebear-$bear.tar.gz";
        $configFile=$wwwRoot.'conf/config.ini';
        if(!file_exists($backupDir)){
            throw new ServerException("$backupDir does not exist");
        }
        if(!file_exists($configFile)){
            throw new ServerException("No config file for icebear-$bear");
        }
        $config=parse_ini_file($configFile);

        if($dbName!==$config['dbName']){
            throw new ServerException("Expected database name $dbName in config, got ".$config['dbName']);
        }

        Log::info('Commencing database dump...');
        $cmd='mysqldump '.$config['dbName'].' --password=\''.$config['dbPass'].'\' --user=\''.$config['dbUser'].'\' --no-tablespaces --single-transaction >'.$backupDir.$sqlFilename;
        $result=exec($cmd,$output);
        if(!file_exists($backupDir.$sqlFilename)){
            throw new ServerException('Database dump '.$backupDir.$sqlFilename.' does not exist after running mysqldump');
        }
        Log::info('...Database dump done.');

        Log::info('Writing code and database dump to tar file...');
        system('tar -czf '.$backupDir.$tarFilename.".tmp -C / var/www/icebear-$bear ".substr($backupDir,1)."$sqlFilename");
        if(!file_exists($backupDir.$tarFilename.'.tmp')){
            throw new ServerException('Tar file '.$backupDir.$tarFilename.'.tmp does not exist after running tar command');
        }
        Log::info('...done.');

        Log::info('Removing database dump (was added to tar file)...');
        @unlink($backupDir.$sqlFilename);
        Log::info('...done.');

        Log::info('Backup succeeded. Rotating old backups...');
        for($i=$backupsToKeep;$i>=1;$i--){
            if(file_exists($backupDir.$tarFilename.'.'.($i-1) )){
                @rename($backupDir.$tarFilename.'.'.($i-1), $backupDir.$tarFilename.'.'.$i);
            }
        }
        @rename($backupDir.$tarFilename, $backupDir.$tarFilename.'.1');
        @rename($backupDir.$tarFilename.'.tmp', $backupDir.$tarFilename);
        Log::info('...done.');

        Log::info("Finished backing up icebear-$bear");
        $succeeded[]=$bear;
    } catch(Exception $e){
        Log::error($e->getMessage());
        Log::error("icebear-$bear backup failed");
        $failed[]=$bear;
    }
    Log::info('----------------------------------');
}
Log::info('Backup run completed.');
if(!empty($failed)){
    Log::error('Backup run completed with errors');
    Log::error('Failed: '.implode(', ', $failed));
}
if(!empty($succeeded)){
    Log::info('Succeeded: '.implode(', ', $succeeded));
}
if(!empty($ignored)){
    Log::info('Ignored: '.implode(', ', $ignored));
}
Log::info('==================================');
Log::info(' ');
