#
# Copyright (c) 2010 Andrea Fazzi
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

require 'rake/clean'
require 'erb'

CLOBBER.concat(['z80_gen.go', 'opcodes_gen.go', 'opcodes_dis_gen.go'])

file "z80" => ["z80.go"] do
  puts "Compile z80.go"
  `go build z80.go`
end

file "z80_dis" => ["z80_dis.go"] do
     puts "Compile z80_dis.go"
     `go build z80_dis.go`
end

file "opcodes_gen.go" => ["z80", "opcodes_gen.go.template"] do
  puts "Write opcodes_gen.go"
  `./z80`

  puts "gofmt opcodes_gen.go"
  `gofmt -w opcodes_gen.go`
end

file "opcodes_dis_gen.go" => ["z80_dis", "opcodes_dis_gen.go.template"] do
  puts "Write opcodes_dis_gen.go"
  `go run z80_dis.go`

  puts "gofmt opcodes_dis_gen.go"
  `gofmt -w opcodes_dis_gen.go`
end

file "z80_gen.go" => ["z80_gen.go.erb"] do
  template = ERB.new(File.read('z80_gen.go.erb'))

  puts "Write z80_gen.go"
  File.open("z80_gen.go", 'w') { |f| f << template.result(binding) }

  puts "gofmt z80_gen.go"
  `gofmt -w z80_gen.go`
end

file "z80_dis_gen.go" => ["z80_dis_gen.go.erb"] do
  template = ERB.new(File.read('z80_dis_gen.go.erb'))

  puts "Write z80_dis_gen.go"
  File.open("z80_dis_gen.go", 'w') { |f| f << template.result(binding) }

  puts "gofmt z80_dis_gen.go"
  `gofmt -w z80_dis_gen.go`
end

task :copy_all => ['z80_gen.go', 'opcodes_gen.go', 'opcodes_dis_gen.go', 'z80_dis_gen.go'] do
  cp "z80_dis_gen.go", "../"
  cp "opcodes_dis_gen.go", "../"
  Dir.chdir("../") do
    sh "go test"
  end
end

task :default => ['z80_gen.go', 'opcodes_gen.go', 'z80_dis_gen.go', 'opcodes_dis_gen.go']
