require_relative 'Creator/parser.rb' require_relative 'Creator/capo.rb' require_relative 'Creator/latex_formatter.rb' require_relative 'Creator/html_formatter.rb' require_relative 'Creator/midi_formatter.rb'

def book

unless $book
  $book = SongBook.parse("Songs")
  # $book.songs.each{|s| s.capo!(2) }
  $book.preface = `tail -n+3 Readme.md | pandoc -t latex`
end
$book

end

def book_name

book.file_safe_title

end

task :parse do

book

end

task :reorder => [:parse] do

File.write("Songs/order.yml", Hash[book.songs.map{|s| [s.order, s.slug]}].to_yaml)

end

task :eps => [:parse] do

mkdir_p 'latex'
Dir.chdir("latex") do
  book.songs.each {|s| s.eps!}
end

end

task :preview => [:parse, :eps, :reorder] do

Dir.chdir("latex") do
  book.preview(filename:book_name)
end

end

desc “Builds PDF out of songbook.” task :pdf => [:parse, :eps, :reorder] do

Dir.chdir("latex") do
  book.build(filename:book_name)
end

end

desc “Builds a booklet PDF out of songbook.” task :booklet => [:parse, :eps, :reorder] do

Dir.chdir("latex") do
  book.build(booklet:true, filename:"#{book_name}let")
end

end

desc “Converts songbook into HTML” task :html => [:parse, :reorder] do

book.to_html("html")

end

desc “Creates midi files for all songs with .abc tunes” task :midi => [:parse, :reorder] do

book.to_midi("html/midi")

end

desc “Creates javascript / JSON descriptions of the songbook” task :info => [:parse] do

File.write("html/#{book_name}.json", book.json_info)
File.write("html/#{book_name}.js", book.jsonp_info)
File.write("html/songbook.json", book.json_info)

end

desc “Creates a portable single file archive of the songbook” task :yaml => [:parse] do

File.write("html/#{book_name}.yml", book.to_yaml)

end

desc “Attempts full build of all output types” task :default => [:midi, :html, :info, :pdf, :booklet] do end

desc “Creates a tex file for each individual song” task :songtex do

b = SongBook.parse("Songs")
Dir.chdir("latex") do
  b.songs.each do |song|
    File.write("#{song.title.downcase.gsub(/[^\w]/,"_")}.tex", SongBook.templatize(song.to_latex))
  end
end

end

task :clean do

Dir.chdir("Songs") do
  system("rm *.pdf *.ps *.eps *.mid")
end
system("rm latex/*")

end

task :toc_to_order do

toc = File.read("latex/#{book_name}let.toc")
nametonum = toc.each_line.map{|l| l.scan(/\\numberline \{(\d+)\}([^\}]+)\}/).flatten.reverse}
File.write('Songs/order.yml', nametonum.map{|name, num| [num.to_i, b.songs.find{|s| s.title == name}.slug]}.to_yaml)

end

task :publish => [:preview, :booklet, :info] do

raise StandardError.new("Uncommited changes") unless `git status -s`.empty?
system("git push")
system("scp -r latex/#{book_name}.pdf latex/#{book_name}let.pdf latex/#{book_name}.json #{book.info["remote_location"]}")

end