<?php
include("include/bittorrent.php");
include("include/benc.php");

function duplicate($id, $hash) {
  $q = "SELECT id, name FROM torrents WHERE info_hash = {$hash} OR id = $id";
  $res=mysql_query($q);
  echo "Torrents duplizieren:<br/>";
  while ($row = mysql_fetch_assoc($res)) {
    echo $row['id'] . ": " . $row['name'] . '<br/>';
  }
  echo "Duplizierung abgeschlossen<br/><hr/>";
}

dbconn();
loggedinorreturn();
if (get_user_class() < UC_ADMINISTRATOR) stderr("Fehler", "<center><h2>Zugang erst ab Rang Administrator!!!</h2></center>");

$torrents = "SELECT id FROM torrents WHERE visible = 'yes' ORDER BY id ";
$res = mysql_query($torrents);
$errors = "";
while ($row = mysql_fetch_assoc($res)) {
  $dict = bdec_file("torrents/" . $row['id'] . ".torrent", 1024*1024);
  if (!isset($dict)) {
    $errors = $row['id'] . ": Datei nicht gefunden<br/>";
    continue;
  }
//  echo "<pre>", print_r($dict), "</pre><br/>";
  $dict = $dict['value']; // easy :P
  if (!isset($dict['info']['string']) || empty($dict['info']['string'])) {
    $errors .= $row['id'] . ": Reparatur fehlgeschlagen (array kann nicht gelesen werden)<br/>";
    echo "<pre>", print_r($dict), "</pre>";
    continue;
  }
  $info_hash = pack("H*", sha1($dict['info']['string']));
  $info_hash = sqlesc($info_hash);
  $query = "UPDATE torrents SET info_hash = {$info_hash} WHERE id = {$row['id']} LIMIT 1";
  if (!mysql_query($query)) {
    $errors .= $row['id'] . ": Reparatur fehlgeschlagen (" . htmlspecialchars($query) . ", " . mysql_error() . ")<br/>";
    duplicate($row['id'], $info_hash);
  }
}
if (empty($errors)) {
  stderr("Status", "<center><h2>Reparatur erfolgreich durchgeführt :D</h2></center>");
}
echo $errors;
?>