var config = require('../config')
var debug = require('debug')('webtorrent-www:tracker')
var downgrade = require('downgrade')
var Tracker = require('bittorrent-tracker/server')
var unlimited = require('unlimited')

unlimited()

// Create WebTorrent-only tracker. Disable UDP and HTTP.
var tracker = new Tracker({ ws: true, udp: false, http: false })

// Redirect http://tracker.webtorrent.io to website homepage
tracker.http.on('request', function (req, res, opts) {
  if (req.method === 'GET' && req.url === '/') {
    res.writeHead(301, { 'Location': 'https://webtorrent.io' })
    res.end()
  }
})

tracker.on('listening', function () {
  debug('listening on %s', tracker.ws.address().port)
  downgrade()
  process.send('ready')
})

tracker.on('warning', function (err) {
  debug('warning: %s', err.message || err)
})

tracker.on('error', function (err) {
  console.error(err.stack || err.message || err)
})

tracker.listen(config.ports.tracker, '127.0.0.1')

@@ -587,16 +587,401 @@
 s.end()%0A
+  %7D else if (req.method === 'GET' && req.url === '/stats') %7B%0A    var infoHashes = Object.keys(tracker.torrents)%0A    var html = '%3Ch1%3E' + infoHashes.length + ' torrents%3C/h1%3E%5Cn'%0A%0A    var list = infoHashes.map(function (infoHash) %7B%0A      return '%3Ca target=%22_blank%22 href=%22https://instant.io/#' + infoHash + '%22%3E' + infoHash + '%3C/a%3E'%0A    %7D)%0A    html += list.join('%5Cn%3Cbr%3E')%0A%0A    res.end(html)%0A
   %7D%0A%7D)%0A%0A

add /stats