#!/usr/bin/env ruby

require 'rake'
require 'mkmf'
#require 'rake/clean.rb'
#require 'file'
require 'ftools'

require 'buildtools.rb'

$LDFLAGS+=" -L/usr/X11R6/lib "
$CFLAGS+=" -I/usr/X11R6/include "

version="0.1.2"

$profile=true
$debug=true


#`mkdir .deps`

def getDestDir
	d="/usr"
	ARGV.each{|l|
		if l=~/DESTDIR=/
			d=l.sub("DESTDIR=","")
		end
	}
	puts "DestDir:"+d
	return d
end


#test_program("swig","Swig was not found! If you make changes on the header-files this can lead to problems.")
#exit


windows # check once

if File.exists?("config.rb")
	puts "Config cached! - remove 'config.rb' or 'rake allclean' to clear cache"
	puts
	require "config.rb"
else
  msh "./configure"
	require "config.rb"
end

begin File.mkpath(".deps")
rescue 
end


interfaceHeadersSRC=["ant_frustum.h","ant_projection.h","ant_camera.h",
"scenenode.h","anim_mesh.h","anim_mesh_data.h","ant_app.h","ant_serial.h","entity.h","entptr.h","glsl.h","height_map.h","map.h","mesh_data.h","mesh.h","mesh_optimizer.h","minimap.h","new_decal.h","ant_renderer.h","resource.h","scene.h","smoke.h","terrain.h","vertex_array.h","water.h"]
interfaceHeadersGUI=[
"ag_rubyobj.h","ag_messageobject.h",
 "ag_geometry.h","ag_font.h","ag_color.h","ag_local.h","ag_config.h",
 "ag_widget.h","ag_colorbutton.h","ag_glwidget.h","ag_xml.h","ag_layout.h","ag_dialog.h","ag_mutex.h",
 "ag_application.h","ag_background.h","ag_border.h","ag_button.h","ag_text.h","ag_caption.h","ag_checkbox.h","ag_combo.h","ag_edit.h","ag_fontengine.h","ag_fs.h","ag_painttarget.h","ag_surface.h","ag_texture.h","ag_surfacemanager.h","ag_image.h","ag_layoutfactory.h","ag_listbox.h","ag_list.h","ag_main.h","ag_menu.h","ag_menuitem.h","ag_mixer.h","ag_mutex.h","ag_painter.h","ag_png.h","ag_radio.h","ag_screen.h","ag_table.h","ag_texturecache.h","ag_theme.h","ag_tools.h","ag_window.h","ag_xml.h"]

# interfaceHeadersGUI=[
# "ag_rubyobj.h",
# "ag_messageobject.h",
#  "ag_geometry.h","ag_font.h","ag_color.h","ag_local.h","ag_config.h",
#  "ag_widget.h","ag_colorbutton.h","ag_glwidget.h","ag_xml.h","ag_layout.h","ag_dialog.h","ag_mutex.h",
#  "ag_application.h","ag_background.h","ag_border.h","ag_button.h","ag_text.h","ag_caption.h","ag_checkbox.h","ag_combo.h","ag_edit.h","ag_fontengine.h","ag_fs.h","ag_painttarget.h","ag_surface.h","ag_texture.h","ag_surfacemanager.h","ag_image.h","ag_layoutfactory.h","ag_listbox.h","ag_list.h","ag_main.h","ag_mixer.h","ag_mutex.h","ag_painter.h","ag_radio.h","ag_screen.h","ag_table.h","ag_texturecache.h","ag_theme.h","ag_tools.h","ag_window.h","ag_xml.h","ag_menuitem.h","ag_menu.h"]
 

PWD=Dir.pwd

task :default => ["libantargis.so"]

$GUISRC="gui/src"
if $ccache!=""
	$ccache+=" "
end

$CFLAGS=""
#puts "CFLAGS:#{$CFLAGS}"

$CXX=$ccache+"g++"
$CC=$ccache+"gcc"
if not windows
	$CFLAGS+=`sdl-config --cflags`.chomp
	$LDFLAGS+=`sdl-config --libs`.chomp+" "+$libs
	$CFLAGS+=" -fPIC"
else
	$CFLAGS="-Ic:/msys/local/include/SDL -Ic:/msys/local/include -Dmain=SDL_main"
	$LDFLAGS="-s -Wl,--enable-auto-import,--export-all "
	$LDFLAGS+=" -Lc:/msys/local/lib -lmingw32 -lSDLmain -lSDL -mwindows "+$libs
end

#if $profile
#	$CFLAGS+=" -pg"
#	$LDFLAGS+=" -pg"
#end


$CFLAGS+=" -Isrc -I"+$GUISRC+" -DUSE_RUBY -I"+Config::CONFIG['archdir']+" -Wall"

if $debug
	$CFLAGS+=" -g -O0"
else
	$CFLAGS+=" -DMNDEBUG -O2"
end
if $profile
	$CFLAGS+=" -DMPROFILE"
end
if $gcdebug
	$CFLAGS+=" -DGCDEBUG"
end

$LDSHARED="#{$CXX} -shared"
$INSTALL_PROG=$INSTALL+" -m 755 -D "
$INSTALL_DATA=$INSTALL+" -m 644 -D "

interfaceHeaders = interfaceHeadersGUI.collect{|x|"../"+$GUISRC+"/"+x} + interfaceHeadersSRC

SRCS=(Dir[$GUISRC+"/*.cc"]+Dir[$GUISRC+"/*.c"]+(Dir["src/*.cc"]-["src/swig.cc"])+["src/swig.cc"]).uniq-[$GUISRC+"/swig.cc"]
OBJS=[]
O2S={}
SRCS.each{|s|
	o=s.gsub(".cc",".o").gsub(".c",".o")
	OBJS<<o
	O2S[o]=s
}

file "libantargis.so" => OBJS do |t|
	msh "#{$LDSHARED} #{$LDFLAGS} -o #{t.name} #{OBJS.join(" ")} "+$libs
end

# manage dependencies

myInterfaces=interfaceHeaders.collect{|x|"src/"+x}+["src/interface.i"]

if $swig!=""
	file ["src/swig.cc"] => ["src/nantmarker.hh"]+myInterfaces do |t|
		msh "cd src; swig -v -Wall -ruby -c++ -I/usr/lib/ruby/1.8/i486-linux -I/usr/include/SDL -o swig.cc interface.i 2>&1"
	end
	
	file ["src/nantmarker.hh"] => myInterfaces do |t|
		msh "cd src; ../#{$GUISRC}/createmarker.rb "+interfaceHeaders.join(" ")
	end
end


SRCS.each{|s|
	dep=".deps/"+s.gsub(/.*\//,"")
	if File.exists?(dep)
		deps=File.open(dep).read.gsub('\\','').gsub(/.*:/,"").split(" ")
	else
		deps=[s]
	end
	if windows
		deps=deps.select{|x|(not x=~/glgl/)}
	end
	if s=~/.cc/
		o=s.gsub(".cc",".o")
		file [o] => deps do |f|
			msh "#{$CXX} #{$CFLAGS} -Wp,-MD,#{dep} -c #{PWD}/#{s} -o #{o} "
# do |x,y| puts "hu" end
		end
	else
		o=s.gsub(".c",".o")
		file [o] => deps do |f|
			msh "#{$CC} #{$CFLAGS} -Wp,-MD,#{dep} -c #{PWD}/#{s} -o #{o} "
		end
	end
}

task :test => "libantargis.so" do |t|
	`ruby ruby/runtests.rb`
	#require 'libantargis.so'
end

task :clean do
	msh "rm -rf clean.rb"
	["src",$GUISRC].each{|dir|
		["*.o","*.oo"].each{|ext|
			msh "rm -rf #{dir}/#{ext}"
		}
	}
	if $swig!=""
		msh "rm -rf src/swig.*"
		msh "rm -rf src/nantmarker.hh"
	end
	msh "rm -rf .deps"
	msh "rm -rf docs/api"
	msh "rm -rf libantargis.so"
end

task :allclean => [:clean] do
	rm_rf "config.rb"
end

def mkdir(d)
	begin
		#puts "mkdir:#{d}"
		Dir.mkdir(d) #sh "test -e #{d} || mkdir #{d}"
	rescue
		#puts "failed"
	end
end
def cpdir(dir,distdir)
	mkdir(distdir+"/"+dir)
	Dir[dir+"/*"].each{|f|
		if (f=~/~/ or f=~/\.o$/ or f=~/\.a$/ or f=~/\.bak/ or f=~/\.xcf/ or f=~/\.svg/ or f=~/\.tar\.gz/ or f=~/antargis-.*/ or f=~/\.iss/ or f=~/vlog\.txt/) and not f=~/\.ogg/
		elsif f=~/\.so/ and not windows
		elsif f=~/Antargis.*package/ or f=~/autopackage/
		elsif File.ftype(f)=="file"
			File.cp(f,"#{distdir}/#{f}")
		end
	}
end

task :install => "libantargis.so" do
	begin
		#puts "PROBLEM: This is not supported ATM"
		#sh $INSTALL_PROG+" libantargis.so "+File.join(Config::CONFIG['sitearchdir'],"libantargis.so")
		destdir=getDestDir
		bindir=destdir+"/bin"
		sharedir=destdir+"/share/antargis"
		#copy everything to sharedir

		md=""
		destdir.split("/").each{|d|
			md+="/"+d
			begin
				#puts "try #{md}"
				Dir.mkdir(md)
			rescue
				#puts "muh"
			end
		}

		mkdir(bindir)
		mkdir(destdir+"/share")
		mkdir(sharedir)
		
		dirs=`find -type d`.split("\n").collect{|x|x.sub("./","")}
		dirs=dirs.select{|x|(not x=~/\.svn/)}.select{|x|(not x=~/\./)}
		dirs=dirs.select{|x|x!="Output" && x!="screenies" && (not x=~/^models/)}
	
		dirs.each{|dir|
			cpdir(dir,sharedir)
		}
		# cp base dir
		cpdir(".",sharedir)

		File.cp("libantargis.so",sharedir+"/libantargis.so")
		f=File.open(bindir+"/antargis","w")
		f.puts('#!/bin/sh
		if test "`echo "$0"|sed -e "s/\/.*//"`" == "" ; then
			d=`dirname $0`
		else
			d=`dirname $(pwd)/$0`
		fi
		p=$(dirname $d)
		s=$(echo "$p/share/antargis")
		c=$(pwd)
		cd $s
		/usr/bin/env ruby run.rb
		cd $c
')
		f.close
		`chmod 755 #{bindir}/antargis`

	rescue
		puts "-----------------------------------------"
		puts "PROBLEM: maybe you have to get root ?"
		puts "-----------------------------------------"
		raise
	end
end


task :dist => :test do
	distdir="antargis-#{version}"
	msh "rm -rf #{distdir}"
	mkdir(distdir)
	#sh "test -e #{distdir} || mkdir #{distdir}"
	dirs=`find -type d`.split("\n").collect{|x|x.sub("./","")}
	dirs=dirs.select{|x|(not x=~/\.svn/)}.select{|x|(not x=~/\./)}
	dirs=dirs.select{|x|x!="Output" && x!="screenies" && (not x=~/^models/)}

	dirs.each{|dir|
		cpdir(dir,distdir)
	}
	# cp base dir
	cpdir(".",distdir)

	if false
		# FIXME: check if png is transparent first
		puts "CONVERTING PNGs to JPGs"
		# make jpgs
		pngs=`find #{distdir} -name "*.png"`
		pngs.split("\n").each{|p|
			n=p.gsub("png","jpg")
			x=`convert #{p} #{n} && rm #{p}`
		}
	end


	# tar.gz
	if not windows
		msh "rm -rf #{distdir}/config.rb"
		msh "tar cfz #{distdir}.tar.gz #{distdir}"
		msh "rm -rf #{distdir}"
	end
	
end

task :doc do
	puts "running doxygen"
	`doxygen Doxyfile`
end
