express = require("express")
fs = require('fs')
https = require('https')
httpProxy = require('http-proxy')
path = require('path')

# where do you want to see our stuff? site must use bootstrap 3!!

#HOST = "http://getbootstrap.com"
HOST = "https://hourlynerd.com"

if process.argv.length == 3
    HOST = process.argv[2]

REPLACEMENTS = { #what kind of evil replacements to make on host? see replacements object for info
    "http://getbootstrap.com": ["bs-logo", "add-hn-css", "add-hn-css-custom"]
    "https://hourlynerd.com": ["add-hn-css", "add-hn-css-custom"]
}[HOST] ? ["add-hn-css", "add-hn-css-custom"]

#add-hn-css-custom adds this:
hnCustomCss = """
<style>
body {
    background-color: #fff;
}
</style>
"""

COMPILE_PATH = "./.compiled"
TEMP_PATH = "./.tmp"
APP_PATH = "./app"
staticRoot = "/hn"

source = fs.readFileSync(path.join(__dirname, ".compiled", "index.html")).toString()

getResources = (type) ->
    re = if type == 'js' then /<script.*src=['"]([^'"]+)/gi else /<link.*href=['"]([^'"]+)/gi
    arr = []
    source.replace(re, (str, m) ->
        return if m.match(/^https?:\/\//)
        if type == 'js'
            tag = "<script src='#{staticRoot}#{m}'></script>"
        else
            tag = "<link rel='stylesheet' href='#{staticRoot}#{m}'></link>"
        arr.push(tag)
    )
    return arr.join("\n")


js = getResources("js")
css = getResources("css")


replacements = {
    "bs-logo": {
        match: '<span class="bs-docs-booticon bs-docs-booticon-lg bs-docs-booticon-outline">B</span>'
        replace: '<span class="bs-docs-booticon bs-docs-booticon-lg bs-docs-booticon-outline">HN</span>'
    },
    "remove-host-js": {
        match: /(<script.*src=['"][^\n]+)/gi
        replace: ''
    },
    "add-hn-css": {
        match: "</body>"
        replace:  "\n\n" + css + "</body>"
    }
    "add-hn-css-custom": {
        match: "</body>"
        replace: "\n\n" + hnCustomCss + "</body>"
    }
    "add-hn-js": {
        match: "</body>"
        replace: "\n\n" + js + "</body>"
    }
}
temp = []
for r in REPLACEMENTS
    temp.push(replacements[r])
replacements = temp



app = express()
proxy = httpProxy.createProxyServer()

proxy.on('proxyReq', (proxyReq, req, res, options) ->
    proxyReq.setHeader("Accept-Encoding", "")
)
proxy.on('proxyRes', (proxyRes, req, res) ->
    delete proxyRes.headers['Content-Length']
)
proxy.on('error', (err, req, res, options) ->
    console.log('proxy error:', err)
)

app.use((req, res, next) ->
    _write = res.write
    _head = res.setHeader

    res.setHeader = (name, value) ->
        _head.apply(res, [name, value]) if name.toLowerCase() != "content-length"

    res.write = (data) ->
        if res._headers['content-type'] == 'text/html; charset=utf-8'
            str = data.toString()
            for obj in replacements
                str = str.replace(obj.match, obj.replace)
            _write.call(res, Buffer(str))
        else
            _write.call(res, data)

    next()
)


app.use(staticRoot, express.static(path.join(__dirname, COMPILE_PATH)))
app.use(staticRoot, express.static(path.join(__dirname, TEMP_PATH)))
app.use(staticRoot, express.static(path.join(__dirname, APP_PATH)))

app.all("*", (req, res) ->
    proxy.web(req, res, {target: HOST, secure: false, changeOrigin: true, rejectUnauthorized: false})
)

app.use((req, res, next) ->
    console.log("404 for:"+req.url)
    res.send(404)
)
app.listen(8090)
console.log("listening on http://localhost:"+ 8090+" -> "+HOST)