const http = require('http'),
    express = require('express'),
    app = express(),
    ts = require('tail-stream'),
    Transform = require('stream').Transform,
    server = http.createServer(app).listen(80, () => {
        console.log(`Listening on: ${server.address().address}:${server.address().port}`)
    })/*.on('connection', socket => {
        socket.setTimeout(300 * 1000)
    })*/

server.keepAliveTimeout = 300 * 1000
server.timeout = 300 * 1000

app.disable('x-powered-by').use('/tail', (req, res, next) => {
    res.header('Content-Type', 'text/event-stream')
    res.header('Connection', 'keep-alive')
    res.header('Cache-Control', 'no-cache')
    const transform = new Transform({
        transform: (chunk, enc, cb) => {
            cb(null, Buffer.from(chunk.toString().replace(/\n/, '\n\ndata: ')))
        }
    })
    res.on('close', () => {
        transform.destroy()
    })
    ts.createReadStream('/access.log', { beginAt: 'end' }).pipe(transform).pipe(res)
}).use('/f2b', (req, res, next) => {
    res.header('Content-Type', 'text/event-stream')
    res.header('Connection', 'keep-alive')
    res.header('Cache-Control', 'no-cache')
    const transform = new Transform({
        transform: (chunk, enc, cb) => {
            cb(null, Buffer.from(chunk.toString().replace(/\n/, '\n\ndata: ')))
        }
    })
    res.on('close', () => {
        transform.destroy()
    })
    ts.createReadStream('/fail2ban.log', { beginAt: 'end' }).pipe(transform).pipe(res)
}).use(express.static(__dirname + '/public'))
