#!/usr/bin/env ruby

begin
#################

require 'logger'
require 'fileutils'
require 'set'

LOGGER = Logger.new(File.join(File.dirname(__FILE__), '..', 'access_log'))

class MercurialError < StandardError; end

ssh_command = ENV["SSH_ORIGINAL_COMMAND"] || ""
match, repo = *ssh_command.match(/^hg -R (\S+) serve --stdio$/)
raise MercurialError, "Could not find a Mercurial repository" unless match

suffix = File.join(".hg", "store")
repos = Mercurial.all

user = ARGV.shift

unless repos.include?(repo)
LOGGER.error "Repository not found for #{user} to #{repo}"
raise MercurialError, "Access denied"
end

unless allowed?
LOGGER.error "Access denied for #{user} to #{repo}"
raise MercurialError, "Access denied"
end

ENV["LOGNAME"] = user
system("hg", "--repository", repo, "serve", "--stdio")
##################
rescue MercurialError => e
abort "[HG] #{e.message}"
rescue NoMemoryError, ScriptError, SignalException, StandardError => e
LOGGER.error "Fat error: #{e.class}: #{e.message}"
LOGGER.error e.backtrace.join("\n")
abort "ERROR: Please email noc@zodal.net"
end

# vim:sts=2:ts=2:sw=2:et:filetype=ruby