#!/usr/bin/ruby

configtest = "/usr/sbin/apachectl configtest"
conffile   = "/etc/httpd/httpd.conf"
backupfile = "#{conffile}.ruby-web.backup.#{Time::now}"
tempfile   = "#{conffile}.ruby-web.temp"

conf = <<-CONF
# begin ruby-web activation
AddHandler cgi-script .rb .rhtml
# end ruby-web activation
CONF

require 'fileutils'
include FileUtils


# ----------- Modify config file ------------

# backup config
cp( conffile, backupfile )

contents = File::open(conffile) do |f|
  f.read
end

config_file_changed = false

unless contents =~ /AddHandler cgi-script .*\.rb/
  contents << "\n\n" << conf
  File.open(tempfile, "w") do |f|
    f.write contents
  end
  
  cp( tempfile, conffile )
  
  config_file_changed = true
end

# ----------- Restart Apache ------------
unless system(configtest)
  if config_file_changed
    puts("[ruby-web #{$0}]: Unable that the Apache webserver is running correcly with the new module and the configuration fiel changes using the '#{configtest}' command.  Ruby-Web itself has been installed sucessfully, but it has not been activated.  Your old #{conffile} file is untouched...")
    puts "[ruby-web #{$0}]: The modified config file is available in '#{tempfile}' so you can examine it and try to activate Ruby-Web"
    
    cp( backupfile, conffile )
  else
    puts "[ruby-web #{$0}]: Unable that the Apache webserver is running correcly with the new module and the configuration fiel changes using the '#{configtest}' command.  Ruby-Web itself has been installed sucessfully, but you need to figure out why Apache is not running.  Your conf file has not been modified."
  end
end
