### codetube
    Copyright (C) 2011 payload payload@lavabit.com
    Copyright (C) 2011 dodo dodo.the.last@gmail.com

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>
###

slug = require('slug')
PostBuffer = require('bufferstream/postbuffer')
HttpBackend = require('../git-http-backend')
Project = require('../models/project')
appconfig = require('../appconfig')
config = require('../config')
Controller = require('./skeleton')
forms = require('../forms')
db = require('../db')
debug_log = require('../helper').debug_log
# TODO watch out, require routes is somehow circular, so it is delayed

class Gits extends Controller
    constructor: () ->
        @httpbackend = new HttpBackend()

    http: (req, res) =>
        req.body = new PostBuffer(req) if req.method is "POST"

        # TODO use more correct git errors

        # each project has some repos like source, wiki or pages
        # default to source if nothing is specified
        p = req.params
        p.repo or= "source"
        unless p.repo in appconfig.repositories
            return res.send(gt._("repo not found."), 404)
        Project.fetch slug(p.owner), slug(p.id), (err, user, project, objs) =>
            return @home(req, res) if @db_failed(err, req)
            # FIXME check if repo is public, access rights etc...
            grp = "git-receive-pack"
            pushing = req.url[-grp.length..] is grp
            needs_auth = pushing
            if needs_auth
                req.authenticate ['git'], (err, authed) =>
                    return res.send(err, 403) if err
                    return if not authed
                    req.session.auth.user.name = req.session.auth.user.username
                    @httpbackend.respond(req, res, project)
            else
                @httpbackend.respond(req, res, project)

# exports

module.exports = Gits

