#!/usr/bin/ruby

DEBUG=false
CVSROOT="/var/cvsroot"

ALIASES=
{
	"alias1" => [ "module1" , "module2", "module3" ],
	"alias2" => [ "module1" , "module2", "module4" ],
}

class CvsAlias

	def initialize(argv)
		parse_arg(argv)
		parse_path
	end

private
	def parse_arg(argv)
		@args = ""
		@cvs_cmd = nil
		index = 0
		next_is_cmd = false
		while index < argv.length - 1
			arg = argv[index]
			unless @cvs_cmd
				if next_is_cmd
					@cvs_cmd = arg
				else
					next_is_cmd = true if arg == CVSROOT
				end
			end
			arg = "'#{arg}'" if arg =~ />/
			@args += " #{arg}";
			index += 1
		end
		@path = argv[index]

		STDERR.print "cmd: #{@cvs_cmd}\n" if DEBUG
		STDERR.print "path: [#{index}] #{@path}\n" if DEBUG
	end

	def parse_path
		if @path =~ %r:/*([^/]+)/(.+):
			@alias = $1
			@real_paths = [$2]
			STDERR.print "HAS SUB: #{$2} for #{@alias}\n" if DEBUG
		elsif @path =~ %r:/*([^/]+)/*$:
			@is_root_path = true
			@alias = $1
			@real_paths = ALIASES[@alias]
			STDERR.print "REAL PATHs: #{@real_paths} for #{@alias}\n" if DEBUG
		else
			STDERR.print "MISC: #{@path}\n" if DEBUG
			@real_paths = [@path]
		end
	end

	def do_cmd(real_path)
		cmd_line = "cvs #{@args} #{real_path}"
		STDERR.print "#{cmd_line}\n" if DEBUG

		result = `#{cmd_line}`

		STDERR.print "original result ==================================" if DEBUG
		STDERR.print result if DEBUG

		result.gsub! %r=RCS file: #{CVSROOT}=, "RCS file: #{CVSROOT}/#{@alias}"

		STDERR.print "modified result ==================================" if DEBUG
		STDERR.print result if DEBUG
		STDERR.print "==================================================" if DEBUG
		print result
	end

public
	def exec_cmd
		if @is_root_path && @cvs_cmd == "rls"
			@real_paths.each do |real_path|
				print "D/#{real_path}////\n"
			end
		else
			@real_paths.each do |real_path|
				do_cmd(real_path)
			end
		end
	end
end

STDERR.print "HOOKED---------\n" if DEBUG

wrap = CvsAlias.new(ARGV)
wrap.exec_cmd
