#!/usr/bin/env python
##
## Copyright 2009 Adriana Lukas & Alec Muffett
##
## Licensed under the Apache License, Version 2.0 (the "License"); you
## may not use this file except in compliance with the License. You
## may obtain a copy of the License at
##
## http://www.apache.org/licenses/LICENSE-2.0
##
## Unless required by applicable law or agreed to in writing, software
## distributed under the License is distributed on an "AS IS" BASIS,
## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
## implied. See the License for the specific language governing
## permissions and limitations under the License.
##

"""
http://docs.djangoproject.com/en/dev/howto/static-files/ says:

<QUOTE>Django itself doesn't serve static (media) files, such as
images, style sheets, or video. It leaves that job to whichever Web
server you choose.  The reasoning here is that standard Web servers,
such as Apache, lighttpd and Cherokee, are much more fine-tuned at
serving static files than a Web application framework.</QUOTE>

...which is fine, but which doesn't actually help us when Django is
being used to implement potentially hundreds of mini-websites with
their own novel forms of authentication and where you don't want
management overhead of keeping (documenting?) how to synchronise their
authentication needs with [INSERT NAME OF PREFERRED WEBSERVER DU
JOUR].

See also: http://code.djangoproject.com/ticket/2131#comment:2

<QUOTE>Django isn't meant to serve static files, so I'm marking this
as a wontfix.</QUOTE>

So in the face of those wanting to nanny us into "proper behaviour",
regrettably we have to roll our own.

We are allowed to take the performance hit, because the point is to
have "one mine per user spattered all over the world" rather than
"bazillion mines all at one hosting company which subsequently suffers
performance issues".
"""

from django.conf import settings
from django.http import HttpResponseNotFound, HttpResponse, HttpResponseRedirect
from django.core.servers.basehttp import FileWrapper
from django.shortcuts import render_to_response
import os
import re

import pymine.util.mimestuff as mimestuff

##################################################################

def cleanpath(old):
    # fasttrack root
    if not old or (old == '/'):
	return ''

    # fault anything with a "?" - we don't do those
    if old.find('?') >= 0:
	raise RuntimeError, "string contains query data: %s" % old

    # is there a trailing slash?
    if old.endswith('/'):
	has_trailing = True
    else:
	has_trailing = False

    # split on slash/multislash
    elements = re.split('/+', old)

    if not elements: return ''

    # delete any trailing empty element
    if elements[-1] == '':
	elements.pop(-1) # explicit

    if not elements: return ''

    # delete any element which is "."
    elements = [ x for x in elements if x != '.' ]

    if not elements: return ''

    # for any element which is "..", delete it and its previous
    output = []
    while elements:
	x = elements.pop(0)
	if x == '..':
	    if output:
		output.pop()
	else:
	    output.append(x)
    elements = output

    if not elements: return ''

    # result
    new = "/".join(elements)

    # reappend trailing slash
    if has_trailing:
	new += '/'

    # join
    return new

##################################################################

def httpserve_error(url_path):
    return HttpResponseNotFound(url_path)

##################################################################

def httpserve_file(file_path, content_type):
    fw = FileWrapper(file(file_path), 65536)
    if not content_type:
	content_type, encoding = mimestuff.lookup.guess_type(file_path)
    response = HttpResponse(fw, content_type=content_type)
    response['Content-Length'] = os.path.getsize(file_path)
    return response

##################################################################

def httpserve_directory(file_path):
    s = {