#!/usr/bin/ruby

require 'pp'
require 'fileutils'
include FileUtils
require 'erb'
require 'rake/testtask'
require 'matrix'
require_relative 'utils'
require 'nokogiri'
import '../help_build.rake'

yab_app_dir = '/usr/local/share/applications/yabasic'
vs=Hash.new
vs['configure.ac']=File.new('lang/configure.ac').read.match(/AC_INIT\(\[yabasic\],\s+\[(\d\.\d+\.\d+)\]\)/)[1]

desc 'Check git'
task :git do
  sh "git diff --exit-code --quiet" do |ok,res|
    if !ok
      sh "git status"
      warn "Uncommited local changes, please fix with 'git add' etc."
    end
  end
end

desc 'Propagate News'
news = News.new('lang/NEWS')
clog = News.new('lang/ChangeLog')
task :news do
  clog.paras.shift if clog.version == news.version
  clog.paras.unshift news.paras[0]
  File.open('lang/ChangeLog','w') do |f|
    f.write clog.as_text + "\n"
    puts "Updated ChangeLog"
  end
  cp 'lang/ChangeLog', '../ChangeLog.org'
  File.open('../tag-message','w') { |f| f.write news.paras[0].as_text + "\n" }
end

desc 'Put version into documentation'
task :xml do
  version_short = vs['configure.ac'].gsub(/\.\d+$/,"")

  $purpose_cnt = Hash.new(0)
  class DefinedHash < Hash # error if key is not defined
    def [](key)
      fail "Undefined key '#{key}'" unless self.key?(key)
      $purpose_cnt[key]+=1
      super(key)
    end
  end
  purpose = DefinedHash.new
  
  doc = File.open("doc/yabasic.xml.erb") { |f| Nokogiri::XML(f) }
  doc.xpath('//refentry').each do |ele|
    purpose[ele.xpath('@id').first.value] = ele.xpath('refnamediv/refpurpose').text
  end
  
  File.open('doc/_yabasic.xml','w') do |file|
    file.write ERB.new(File.read('doc/yabasic.xml.erb')).result(binding)
  end
  diff = purpose.keys - $purpose_cnt.keys - %w(backcolour color)
  fail "These keys have not been used: #{diff}" if diff.length > 0
end

desc 'Create html doc from xml'
task :html => :xml do
  ENV['SGML_CATALOG_FILES']='/etc/xml/catalog'
  sh 'xsltproc --stringparam html.stylesheet docbook.css doc/mystyle.xsl doc/_yabasic.xml >lang/yabasic.htm'
  cp 'lang/yabasic.htm', '../products'
end

desc 'Create man page'
task :man => :html do
  sh 'w3m -dump -o display_charset=ascii,cols=74 lang/yabasic.htm >/tmp/y.utf8'
  ascii = File.new('/tmp/y.utf8').read.lines.map {|x| " " + x}.join
  open('lang/yabasic.1','w') {|f| f.write ERB.new(File.new('doc/yabasic.1.erb').read).result(binding)}
end

desc 'Create configure'
file 'lang/configure' => 'lang/configure.ac' do
  cd ('lang') { sh 'autoconf' }
end

desc 'Create Makefile.in'
file 'lang/Makefile.in' => 'lang/Makefile.am' do
  cd ('lang') { sh 'automake' }
end

desc 'Create Makefile'
file 'lang/Makefile' => ['lang/Makefile.in','lang/configure'] do
  cd ('lang') do
    sh 'configure'
    sh 'config.status'
  end
end

desc 'Run make'
task :make => 'lang/yabasic.1' do
  cd ('lang') do
    sh 'make bison'
    sh 'make flex'
    sh 'make clean'
    sh 'make'
  end
end

desc 'Run tests'
task :tests => :make do
  cd 'lang' do
    run_tests './tests', '../yabasic'
    run_tests './tests/common', '../../yabasic'
    run_tests './tests/error', '../../yabasic'
  end
end

desc 'Run tests immediately'
task :t do
  cd 'lang' do
    run_tests './tests', '../yabasic'
    run_tests './tests/common', '../../yabasic'
    run_tests './tests/error', '../../yabasic'
  end
end

desc 'Run tests immediately, part1'
task :t1 do
  cd 'lang' do
    run_tests './tests', '../yabasic'
  end
end

desc 'Run tests immediately, part2'
task :t2 do
  cd 'lang' do
    run_tests './tests/common', '../../yabasic'
  end
end

desc 'Run tests immediately, part3'
task :t3 do
  cd 'lang' do
    run_tests './tests/error', '../../yabasic'
  end
end

desc 'Run autoconf checks'
task :check => :tests do
  cd 'lang' do
    sh 'make check'
  end
end

desc 'Collect Versions'
task :versions => [:git,:html,:tests,'lang/Makefile','lang/configure',:news] do
  vs['yabasic']=%x( lang/yabasic -v 2>&1 ).match(/yabasic (\d\.\d+\.\d+)/ )[1]
  vs['yabasic.htm']=File.new('lang/yabasic.htm').read.match(/This document applies to version\s+.*(\d\.\d+)/)[1]
  vs['NEWS']=news.version;
  pp vs
  fail "Mismatch between versions of 'yabasic' and 'yabasic.htm'" if (vs['yabasic'].to_f-vs['yabasic.htm'].to_f).abs >= 0.01
  fail "Mismatch between versions of 'yabasic' and 'configure.ac'" if vs['yabasic'] != vs['configure.ac']
  fail "Mismatch between versions of 'NEWS' and 'configure.ac'" if vs['NEWS'] != vs['configure.ac']
end

desc 'Create tar with sources'
task :sources => [:news,:versions] do
  cd 'lang' do
    rm 'tests/bind_import'
    rm 'tests/nested_bind_import'
    sh 'make dist-gzip'
    mv "yabasic-#{vs['yabasic']}.tar.gz", '../../products'
  end
end
  
desc 'Create rpm and debian'
task :rpm => :sources do
  cd "lang" do
    sh "make install DESTDIR=#{Dir.pwd}/pkg"
    mkdir_p "pkg/#{yab_app_dir}"
    %w( demo.yab yabasic.htm ).each do |file|
      cp file, "pkg/#{yab_app_dir}"
    end
    %w( rpm deb ).each do |fmt|
      sh "fpm -f -s dir -t #{fmt} -n yabasic -v #{vs['yabasic']} -C pkg"
    end
    mv "yabasic-#{vs['yabasic']}-1.x86_64.rpm",'../../products'
    mv "yabasic_#{vs['yabasic']}_amd64.deb",'../../products'
  end
end

desc 'Cleanup and show products'
task :default => [:news,:check, 'lang/yabasic.1', :html, :rpm, :sources] do
  rm Dir.glob('../products/web/download/*')
  prod_globs = %w( yabasic*.x86_64.rpm yabasic*amd64.deb yabasic*.tar.gz )
  prod_globs.each { |glob| cleanup "../products/#{glob}" }
  sh "ls -lrt ../products"
end

