<?php

require_once("include/bittorrent.php");
require_once("include/benc.php");

if (!isset($_GET["peer_id"]))
{
    if($_GET["download"])
    {
        $dict['type'] = "dictionary";
        $dict['value']['announce']['type'] = "string";
        $dict['value']['announce']['value'] = "$BASEURL/agentident.php";
        $dict['value']['info']['type'] = "dictionary";
        $dict['value']['info']['value']['length']['type'] = "integer";
        $dict['value']['info']['value']['length']['value'] = 1;
        $dict['value']['info']['value']['name']['type'] = "string";
        $dict['value']['info']['value']['name']['value'] = "test.txt";
        $dict['value']['info']['value']['piece length']['type'] = "integer";
        $dict['value']['info']['value']['piece length']['value'] = 32768;
        $dict['value']['info']['value']['pieces']['type'] = "string";
        $dict['value']['info']['value']['pieces']['value'] = pack("H*", sha1(rand(0, 1)));

        header("Content-Type: application/x-bittorrent");
        header("Content-Disposition: attachment; filename=\"test.torrent\"");

        print(benc($dict));
    }
    else
    {
        print("<html><body><p><a href=\"agentident.php?download=1\">Download Test Torrent</a><p>".
        "<p>Download and run the test torrent above. Once you run the torrent in your ".
        "client it should generate this error message:</p>".
        "<p><pre>Error: agt: &lt;AGENT&gt; pid: &lt;PEERID&gt;</pre></p>".
        "<p>where, <pre>&lt;AGENT&gt;</pre> is your client's agent and, <pre>&lt;PEERID&gt;</pre>".
        "is your current peerid.</p></body></html>");
    }
}
else
{
    $message = "agt: ".$_SERVER["HTTP_USER_AGENT"]." pid: ".$_GET["peer_id"];
    $benc_resp = benc(array(type => "dictionary", value => array("failure reason" => array(type => "string", value => $message))));

    header("Content-Type: text/plain");
    header("Pragma: no-cache");
    print($benc_resp);
}

?>