backup.php 1.17 KB
Newer Older
dmorley's avatar
backup  
dmorley committed
1
<?php
2

3 4 5 6 7 8
/**
 * Backup / dump PostgreSQL database.
 */

declare(strict_types=1);

dmorley's avatar
dmorley committed
9 10 11
require_once __DIR__ . '/../boot.php';

if (!is_cli()) {
12 13
    header('HTTP/1.0 403 Forbidden');
    exit;
14 15
}

dmorley's avatar
dmorley committed
16 17 18
$keep_for    = 60 * 60 * 6; // 6 hours
$backup_file = c('backup_dir') . '/dump_' . date('Ymd_His') . '.sql';

dmorley's avatar
dmorley committed
19
debug("Making backup of '%s' to '%s'...", c('pgdb'), $backup_file);
dmorley's avatar
dmorley committed
20 21 22 23 24 25 26 27 28
system(sprintf(
    'export PGPASSWORD=%3$s &&' .
    '"%1$s" --clean --format=tar --username=%2$s %4$s >> "%5$s"',
    c('pg_dump_dir') . '/pg_dump',
    c('pguser'),
    c('pgpass'),
    c('pgdb'),
    $backup_file
), $exit_code);
dmorley's avatar
dmorley committed
29 30 31 32 33

if ($exit_code === 0) {
    updateMeta('backup');
}

dmorley's avatar
dmorley committed
34
debug(" %s\n", $exit_code === 0 ? 'Success!' : 'Failed.');
35

dmorley's avatar
dmorley committed
36
$dirh = dir(c('backup_dir'));
37
while ($entry = $dirh->read()) {
dmorley's avatar
dmorley committed
38 39 40 41 42
    $file = c('backup_dir') . "/{$entry}";

    // Skip dotfiles and non-files (folders, symlinks, etc.).
    if ($entry[0] === '.' || !is_file($file)) {
        continue;
dmorley's avatar
cleanup  
dmorley committed
43
    }
dmorley's avatar
dmorley committed
44 45 46 47 48 49 50 51 52 53 54

    if (filectime($file) + $keep_for > time()) {
        //echo "Don't delete {$entry}\n";
        continue;
    }

    printf(
        "Removing old file '%s'... %s\n",
        $entry,
        unlink($file) ? 'Success!' : 'Failed.'
    );
dmorley's avatar
backup  
dmorley committed
55
}