# Rakefile template for building C code.
#
# Outputs to a separate build tree
# Escapes filenames correctly (for bash at least).
#
# Author: mark at markferry dot net
# Licence: public domain, use it as you wish
#
require 'rake/clean'
require 'shellwords'

## Tasks
Dir['tasks/*.rake'].each { |f| import f }

##### Inputs ######
SRC_DIR = "src"

# Not working. Needs pathmap variables
CONFIG = ENV["CONFIG"] || "Release"

## Arch-ABI-Configuration
ARCH = "x86"
ABI = "gnuabi"
AAC = [ARCH, ABI, CONFIG].join('-')

OBJ_DIR = File.join("build", AAC)
DIST_DIR = File.join("dist", AAC)

PROJ = "raketest"

DIST_EXE = File.join(DIST_DIR, PROJ).ext('exe')

## CC
CC = "gcc"

C_SRCS = FileList["#{SRC_DIR}/*\*/\*.c"]

def to_obj(objdir, f)
  f.sub(/^#{SRC_DIR}/, objdir).ext('.o')
end

C\_OBJS = C\_SRCS.map { |f|
  to_obj(OBJ_DIR, f)
}

##### Targets ######
CLEAN.include C_OBJS
CLEAN.include DIST_DIR

directory OBJ_DIR
directory DIST_DIR

# Create output dirs for each include dir
C_OBJS.each do |d|
  directory d.pathmap('%d')
end

task :default => :build

desc "Build"
task :build => DIST_EXE

task :info do
  p C_SRCS
  p C_OBJS
  p DIST_EXE
end

##### Rules ######

## CC
rule '.o' => [
    proc { |tn| tn.sub(/#{OBJ\_DIR}/, SRC\_DIR).ext('.c') },
    '%d'
  ] do |t|
  sh %Q{#{CC} -c #{t.source.shellescape} -o #{t.name.shellescape}}
end

## LD
rule '.exe' => [*C_OBJS, '%d'] do |t|
  sh %Q{#{CC} -o #{t.name.shellescape} #{C_OBJS.shelljoin}}
end