<?php

/*
 * Script that deletes old versions of repo.
 * Only run on installations using date-time tag as version identifier.
 * Arguments:
 *  keep: number of versions to keep (removes all other)
 *  path: path to directory that contain the "version" directory and "current" symlink
 */

preg_match('|(.*)/version/|', __DIR__, $matches);

$opts = array_merge([
    'keep' => 3,
    'path' => isset($matches[1]) ? $matches[1] : null,
], getopt('', ['keep:', 'path:']));

if (!$opts['path'] || !file_exists($opts['path'])) {
    die("Invalid path, aborting\n");
}

// Locate relevant file nodes
$current = file_exists("{$opts['path']}/current") ? readlink("{$opts['path']}/current") : null;
$versions = glob("{$opts['path']}/version/*", GLOB_ONLYDIR);
$version_count = count($versions);

if ($version_count <= $opts['keep']) {
    exit(); // Nothing to remove
}

// Never remove current version
if ($current) {
    $match = array_search($current, $versions);
    if ($match !== false) {
        unset($versions[$match]);
    }
}

// Remove versions not specified for keeping
$remove = implode(' ', array_slice($versions, 0, $version_count - $opts['keep']));
if ($remove) {
    exec("rm -rf {$remove}");
}
