#! /usr/bin/env ruby

require 'getoptlong'
require 'rbconfig'
require 'ftools'
require 'find'

INSTDIR = File.join Config::CONFIG['sitedir'], 
	"#{Config::CONFIG['MAJOR']}.#{Config::CONFIG['MINOR']}"

opts = GetoptLong.new( 
	[ "--uninstall",	"-u",		GetoptLong::NO_ARGUMENT ],
	[ "--i-have-racc",	"-r",		GetoptLong::NO_ARGUMENT ],
    [ "--destdir",      "-d",       GetoptLong::REQUIRED_ARGUMENT ]
)

def install( force = false, dir = INSTDIR )
	begin
		yaml_rb = File.join( "src", "yaml.rb" )
		unless File.exists?( yaml_rb ) and not force
			#
			# Generate the parser
			#
			racc = `which racc`.strip
			if not racc
				puts "RACC not found.  Please install RACC from http://www.ruby-lang.org/en/raa-list.rhtml?name=Racc and run install again."
				exit
			end

			`#{racc} -v -E src/yaml.y.rb -o src/yaml.rb`
		end
				
        unless File.exists?( File.join( dir, "okay" ) )
            Dir.mkdir( File.join( dir, "okay" ) )
        end
		install_files = {
			yaml_rb => File.join( dir, "yaml.rb" ),
			File.join( "src", "okay.rb" ) => File.join( dir, "okay.rb" ),
			File.join( "src", "okay", "news.rb" ) => File.join( dir, "okay", "news.rb" ),
			File.join( "src", "okay", "rpc.rb" ) => File.join( dir, "okay", "rpc.rb" ),
			File.join( "src", "yod.rb" ) => File.join( dir, "yod.rb" )
		}
		install_files.each_pair { |src, dst|
			if File.exists?( dst )
			    File.delete( dst )
			end
			File.install(src, dst, 0644, true)
	  	}
	rescue
		puts $!
	end
end

def uninstall
	begin
		File.delete( File.join( INSTDIR, "yaml.rb" ) )
		File.delete( File.join( INSTDIR, "yod.rb" ) )
		File.delete( File.join( INSTDIR, "okay.rb" ) )
		File.delete( File.join( INSTDIR, "okay", "news.rb" ) )
		File.delete( File.join( INSTDIR, "okay", "rpc.rb" ) )
		puts "Uninstalled YAML.rb."
	rescue
		puts "YAML.rb not found."
	end
end

install_proc = :install
install_force = false
install_dir = INSTDIR
opts.each do |opts, arg|
	case opts
		when "--uninstall"
			install_proc = :uninstall
		when "--i-have-racc"
			install_force = true
        when "--destdir"
            install_dir = arg
	end
end
send( install_proc, install_force, install_dir )
