#! /usr/bin/env php
<?php

/**
 * Script to clean broken uploads
 *
 * Usage: remove-upload <admin-id> <torrent-id> [<torrent-id> ...]
 */

namespace Gazelle;

require __DIR__ . '/../lib/bootstrap.php';

$torMan  = new Manager\Torrent();
$userMan = new Manager\User();
$reward  = new BonusUploadReward();

array_shift($argv);
$janitorId = array_shift($argv);
$janitor = $userMan->find($janitorId);
if (is_null($janitor)) {
    die("No janitor [$janitorId]\n");
}

foreach ($argv as $torrentId) {
    $torrent = $torMan->findById($torrentId);
    if (is_null($torrent)) {
        echo "No such torrent $torrentId\n";
        continue;
    }
    $name = $torrent->group()->text()
        . ' [' . implode('/', [$torrent->media(), $torrent->format(), $torrent->encoding()]) . ']';
    $uploader = $torrent->uploader();
    $points = 2 * $reward->reward($torrent);

    [$success, $message] = $torrent->removeTorrent($janitor, "Broken upload - backend");
    if (!$success) {
        echo "Did not remove $torrentId: $message\n";
        continue;
    }

    new User\Bonus($uploader)->addPoints($points);
    $uploader->inbox()->createSystem(
        "Your upload $name has been removed",
        "Due to a transient bug, your upload $name was not completed by the backend. Since it did not break any rules (we hope), please feel free to re-upload it. Since this is on us, you have been gifted $points points."
    );
    echo "removed $torrentId ($name) for $points points, uploaded by " . $uploader->username() . "\n";
}
