#!/usr/bin/env ruby

RAILS_ENV = 'add_project'

require 'optparse'

scm_options = {:interactive => true}
trace = false

if ARGV.first and ARGV.first !~ /^-/
  project_name = ARGV.shift
  if ARGV.first and ARGV.first !~ /^-/
    scm_options[:repository] = ARGV.shift
  end
end

ARGV.options do |opts|
  opts.banner = "usage: add [project-name] -r [repository] -s [svn|git|hg|bzr]"

  opts.separator ""

  opts.on("-r", "--repository repository", String,
          "Location of the source control repository for the project (eg. svn://rubyforge.org/var/svn/cruisecontrolrb)") do |v|
    scm_options[:repository] = v
  end

  opts.on("-s", "--source-control source_control", String,
          "Specify the source control manager to use (default: subversion)") do |v|
    scm_options[:source_control] = v
  end
  opts.on("-b", "--branch branch", String, "Specify a source control branch to use (Git, Mercurial)") { |v| scm_options[:branch] = v }
  opts.on("--username username", String, "Specify a username for source control") { |v| scm_options[:username] = v }
  opts.on("--password password", String, "Specify a password for source control") { |v| scm_options[:password] = v }
  opts.on('-t', '--trace', 'Print out exception stack traces') { trace = true }

  opts.separator ""

  opts.on("-u", "--url url", String,
          "[deprecated, use -r|--repository instead] URL of the source control repository") do |v|
    scm_options[:repository] = v
  end

  opts.separator ""

  opts.on("-h", "--help", "Show this help message.") { puts opts; exit }

  args = opts.parse!

  unless project_name and scm_options[:repository]
    STDERR.puts "Project name and repository location are mandatory"
    STDERR.puts
    puts opts
    exit(-1)
  end

  # Project Name can only contain alphanumeric characters
  if project_name.match /[^-_a-zA-Z0-9]/
    STDERR.puts "'#{project_name}' is not a valid project name. Project name should only contain alphanumeric " +
        'characters, dashes and underscores, and no whitespace.'
    exit(-1)
  end
end

puts "Adding project '#{project_name}' (this may take a while)..."

begin 

  require File.dirname(__FILE__) + '/../config/boot'
  require RAILS_ROOT + "/config/environment"

  source_control = SourceControl.create(scm_options)

  project = Project.new(project_name, source_control)
	projects = Projects.load_all
	projects << project
	
	if source_control.repository =~ /^svn\+ssh\:\/\//
    puts "IMPORTANT!!! - It looks like you are connecting to your repository with an svn+ssh connection.  " +
         "For cruise to build this project, you need to have set up authentication caching for ssh, see this article"
    puts "   http://subversion.tigris.org/faq.html#ssh-auth-cache"
    puts
  end

rescue => e
  STDERR.puts "FAILED: #{e.message}"
  if trace
    STDERR.puts e.backtrace.map { |line| "    #{line}" }
  end
  exit(-1)
end

puts "Project '#{project_name}' added."