#!/usr/bin/ruby

require 'cgi'

class Servlet
  CHECKOUT   = 'svn checkout --non-interactive --username X --password P'
  UPDATE     = 'svn update   --non-interactive --username X --password P'
  URL        = 'http://subversion.assembla.com/svn/spacename'
  DEPLOY_DIR = "/tmp/spacename"

  #--------------------------------------------------
  # Process CGI request
  def cgi_process_request
    @cgi = CGI.new('html4')
    code = 'OK'
    comment = ''

    # Assembla may test if we are alive
    if @cgi['project'].empty?
      code = 'OK'
      comment = 'Deploy agent is alive'

    # Deploy the application
    else
      if ! File.directory?(DEPLOY_DIR)
        buildlog = `#{CHECKOUT} #{URL} #{DEPLOY_DIR} 2>&1`
      else
        buildlog = `#{UPDATE} #{DEPLOY_DIR} 2>&1`
      end

      if $? != 0
        code = 'NOT_FOUND'
        comment = "Unable to deploy from URL #{URL}"
      end
    end

    @cgi.out("status"     => code,
             "type"       => "text/html") {comment}
  end

end

Servlet.new.cgi_process_request

