# -*- ruby -*-
#
# $Id$
#
# xmlresume2x: converts an xml resume to various output formats
# Copyright (C) 2004 Thomas Leitner
#
# This program is free software; you can redistribute it and/or modify it under the terms of the GNU
# General Public License as published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with this program; if not,
# write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#


begin
  require 'rubygems'
  require 'rake/gempackagetask'
rescue Exception
  nil
end

require 'rake/clean'
require 'rake/packagetask'
require 'rake/rdoctask'
require 'rake/testtask'

# General actions  ##############################################################

$:.push "lib"
require 'xmlresume2x/converter'

PKG_NAME = "xmlresume2x"
PKG_VERSION = XMLResume2x::VERSION.join( '.' )
PKG_FULLNAME = PKG_NAME + "-" + PKG_VERSION
PKG_SUMMARY = "Converts an xml resume to various output formats"
PKG_DESCRIPTION = "xmlresume2x can convert CVs written in the XML Resume
Library format (http://xmlresume.sourceforge.net) to a number
of formats, including LaTeX markup which uses the europecv
(http://www.ctan.org/tex-archive/help/Catalogue/entries/europecv.html)
class which is based on the 'standard' European Curriculum Vitae
format at http://www.cedefop.eu.int/transparency/cv.asp."

SRC_RB = FileList['lib/**/*.rb', 'bin/**/*', 'data/**/*.cfg']

# The default task is run if rake is given no explicit arguments.

desc "Default Task"
task :default => :version


# End user tasks ################################################################

desc "Prepares for installation"
task :prepare do
  ruby "setup.rb config"
  ruby "setup.rb setup"
end


desc "Installs the package #{PKG_NAME}"
task :install => [:prepare] do
  ruby "setup.rb install"
end


task :clean do
  ruby "setup.rb clean"
end


CLOBBER << "doc/output" << FileList['texput.*'].to_a
desc "Builds the documentation (needs webgen and LaTeX with latex-europecv package installed)"
task :doc => [:rdoc, :gen_version] do
  chdir "doc" do
    sh "webgen -V 3"
  end

  ruby "-Ilib bin/xmlresume2x -d data/xmlresume2x -f xhtml -l en testfiles/example1.xml > doc/output/examples/example1styled.html"
  sh "sed -e '7 d' doc/output/examples/example1styled.html > doc/output/examples/example1.html"
  ruby "-Ilib bin/xmlresume2x -d data/xmlresume2x -f xhtml -l en testfiles/example2.xml > doc/output/examples/example2styled.html"
  sh "sed -e '7 d' doc/output/examples/example2styled.html > doc/output/examples/example2.html"
  cp "data/xmlresume2x/misc/css/blue.css", "doc/output/examples/cv.css"

  ruby "-Ilib bin/xmlresume2x -d data/xmlresume2x -f latex-europecv -l en testfiles/example1.xml > texput.tex"
  sh "latex texput.tex"
  sh "dvipdf texput.dvi doc/output/examples/example1.pdf"
  ruby "-Ilib bin/xmlresume2x -d data/xmlresume2x -f latex-europecv -l en testfiles/example2.xml > texput.tex"
  sh "latex texput.tex"
  sh "dvipdf texput.dvi doc/output/examples/example2.pdf"

  cp FileList["testfiles/example*.xml"].to_a, "doc/output/examples"
  cp ["misc/dtd/resume.dtd", "misc/dtd/iso-lat1.ent"].to_a, "doc/output/examples"
end

rd = Rake::RDocTask.new do |rdoc|
  rdoc.rdoc_dir = 'doc/output/rdoc'
  rdoc.title    = PKG_NAME
  rdoc.options << '--line-numbers' << '--inline-source' << '-m README'
  rdoc.rdoc_files.include( 'README' )
  rdoc.rdoc_files.include( 'lib/**/*.rb' )
end

# Developer tasks ##############################################################

PKG_FILES = FileList.new( [
                            'setup.rb',
                            'TODO',
                            'COPYING',
                            'README',
                            'Rakefile',
                            'ChangeLog',
                            'VERSION',
                            'install.rb',
                            'bin/**/*',
                            'lib/**/*.rb',
                            'doc/**/*',
                            'test/**/*',
                            'data/**/*'
                          ]) do |fl|
  fl.exclude( /\bsvn\b/ )
  fl.exclude( 'doc/output' )
end

task :package => [:gen_files] do
  chdir 'pkg' do
    sh "rpaadmin packport #{PKG_NAME}-#{PKG_VERSION}"
  end
end

task :gen_changelog do
  sh "svn log -r HEAD:1 -v > ChangeLog"
end

task :gen_version do
  puts "Generating VERSION file"
  File.open( 'VERSION', 'w+' ) do |file| file.write( PKG_VERSION + "\n" ) end
end

task :gen_installrb do
  puts "Generating install.rb file"
  File.open( 'install.rb', 'w+' ) do |file|
    file.write "
require 'rpa/install'

class Install_#{PKG_NAME} < RPA::Install::FullInstaller
  name '#{PKG_NAME}'
  version '#{PKG_VERSION}-1'
  classification Application
  build do
    installdocs %w[COPYING ChangeLog TODO]
    installdocs 'docs'
    installrdoc %w[README] + Dir['lib/**/*.rb']
    installdata
  end
  description <<-EOF
#{PKG_SUMMARY}

#{PKG_DESCRIPTION}
  EOF
end
"
    end
end

task :gen_files => [:gen_changelog, :gen_version, :gen_installrb]
CLOBBER << "ChangeLog" << "VERSION" << "install.rb"

Rake::PackageTask.new( PKG_NAME, PKG_VERSION ) do |p|
  p.need_tar = true
  p.need_zip = true
  p.package_files = PKG_FILES
end

if defined? Gem
  spec = Gem::Specification.new do |s|

    #### Basic information

    s.name = PKG_NAME
    s.version = PKG_VERSION
    s.summary = PKG_SUMMARY
    s.description = PKG_DESCRIPTION

    #### Dependencies, requirements and files

    s.files = PKG_FILES.to_a

    s.require_path = 'lib'
    s.autorequire = nil
    s.executables = ['xmlresume2x']
    s.default_executable = 'xmlresume2x'

    #### Documentation

    s.has_rdoc = true
    s.extra_rdoc_files = rd.rdoc_files.reject do |fn| fn =~ /\.rb$/ end.to_a
    s.rdoc_options = ['--line-numbers', '-m README']

    #### Author and project details

    s.author = "Thomas Leitner"
    s.email = "t_leitner@gmx.at"
    s.homepage = "xmlresume2x.rubyforge.org"
    s.rubyforge_project = "xmlresume2x"
  end

  Rake::GemPackageTask.new( spec ) do |pkg|
    pkg.need_zip = true
    pkg.need_tar = true
  end
end


desc "Creates a tag in the repository"
task :tag do
  repositoryPath = File.dirname( $1 ) if `svn info` =~ /^URL: (.*)$/
  fail "Tag already created in repository " if /#{PKG_FULLNAME}/ =~ `svn ls #{repositoryPath}/versions`
  sh "svn cp -m 'Created version #{PKG_FULLNAME}' #{repositoryPath}/trunk #{repositoryPath}/versions/#{PKG_FULLNAME}"
end

desc "Upload documentation to homepage"
task :uploaddoc => [:doc] do
  Dir.chdir('doc/output')
  sh "scp -r * gettalong@rubyforge.org:/var/www/gforge-projects/#{PKG_NAME}/"
end


# Misc tasks ###################################################################


def count_lines( filename )
  lines = 0
  codelines = 0
  open( filename ) do |f|
    f.each do |line|
      lines += 1
      next if line =~ /^\s*$/
      next if line =~ /^\s*#/
      codelines += 1
    end
  end
  [lines, codelines]
end


def show_line( msg, lines, loc )
  printf "%6s %6s   %s\n", lines.to_s, loc.to_s, msg
end

desc "Show statistics"
task :statistics do
  total_lines = 0
  total_code = 0
  show_line( "File Name", "Lines", "LOC" )
  SRC_RB.each do |fn|
    lines, codelines = count_lines fn
    show_line( fn, lines, codelines )
    total_lines += lines
    total_code  += codelines
  end
  show_line( "Total", total_lines, total_code )
end


desc "Show unprocessed elements"
task :missing do
  require 'set'
  elements = File.read( 'misc/dtd/resume.dtd' ).scan( /^(<!ELEMENT\s)(\w+)\s(?!\(#PCDATA\))/ ).collect {|i| i[1]}.to_set
  Dir['data/xmlresume2x/format/*.cfg'].each do |file|
    processor = XMLResume2x::ResumeProcessor.new( 'en' )
    processor.load_config( File.read( file ) )
    processed = processor.assignments.keys
    e = elements.dup
    e.subtract( processed )
    puts "Missing elements for format file #{file}:"
    puts e.to_a.sort.join( ", " )
  end
end
