from hashlib import md5
from time import sleep
import os

with open('/etc/hosts') as handle:
    content = handle.read()
content_hash = '"' + md5(content).hexdigest() + '"'


def application(environ, start_response):
    def index():
        start_response("200 OK", [("Content-Type", "text/html")])
        yield '<html><body><a href="/test">test</a></body></html>'

    def initial():
        status = "200 OK"
        start_response(status, [
            ('Content-Type', 'application/javascript'),
            ('Cache-Control', 's-maxage=0, private, must-revalidate, max-age=0'),
            ('Content-Length', str(len(content))),
            ('ETag', content_hash),
        ])
        middle_position = len(content)/2
        yield content[:middle_position]
        os.system('pkill -9 uwsgi') # simulate a crash
        sleep(1)
        yield content[middle_position:]

    def cached():
        start_response("304 NOT MODIFIED", [])
        yield ''

    if 'test' not in environ['REQUEST_URI']:
        return index()
    if environ.get('HTTP_IF_NONE_MATCH') == content_hash:
        return cached()
    return initial()
