#!/usr/bin/ruby

require 'pp'
require 'fileutils'
include FileUtils
require 'erb'
require_relative '../unix/utils.rb'
require 'io/console'
import '../help_build.rake'

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

version = nil
html_with_latest_news = nil
html_with_all_news = nil

desc 'Collect news'
task :version => :git do
  version_file = '../windows/resources/yabver.txt'
  version = File.read(version_file).chomp.strip
  puts "Version #{version}"
  news_file = '../unix/lang/NEWS'
  news = News.new(news_file)
  fail "Versions from #{news_file} (#{news.version}) and #{version_file} (#{version}) do not match" if news.version != version
  html_with_latest_news = news.as_html_all(4)
  fragname = "fragment_log.html"
  frag = File.new(fragname).read
  unless frag.include?("Version #{version}")
    frag = news.as_html(3) + "\n" + frag
    File.new(fragname,"w").write(frag)
    puts "Wrote #{fragname}"
  end
  html_with_all_news = frag
end

# colors from https://color.adobe.com
colors_legacy = { :toc_bg => "#FFBD7C",
                  :head_bg => "#79BD8F",
                  :head_biggest => "#00A388",
                  :head_small => "#46573B",
                  :head_bigger => "#46573B"}

colors_blueish = { :toc_bg => "#29D9C2",
                   :head_bg => "#01AEB2",
                   :head_biggest => "#29D9C2",
                   :head_small => "#FFFFA6",
                   :head_bigger => "#FFFFA6"}

colors = colors_blueish

generated_html = Array.new

desc 'Process erb templates'
task :templates => :version do
  %w( content_download.html.erb content_whatsnew.html.erb content_log.html.erb head.html.erb toc.html.erb ).each do |name|
    generated = name.chomp('.erb')
    generated_html << generated
    File.open(generated,'w') do |file|
      file.write ERB.new(File.read(name)).result(binding)
    end
  end

  structure=File.read('structure.html.erb')
  %w( index.html download.html whatsnew.html support.html screenshots.html copyright.html related.html faq.html history.html log.html manual_yabasic.html mit.html changing.html ).each do |name|
    if name == 'manual_yabasic.html'
      frame_html = 'yabasic.htm'
    elsif name == 'index.html'
      frame_html = 'content_whatsnew.html'
    else
      frame_html = "content_#{name}"
    end
    
    puts "#{name} wraps #{frame_html}"
    generated_html << name
    File.open(name,'w') do |file|
      file.write ERB.new(structure).result(binding)
    end
  end
end

desc 'Copy content'
task :copy => :templates do
  todir = '../products/web'
  rm_rf todir if File.exists?(todir)
  cp_r '../web','../products'
  Dir["#{todir}/*.erb"].each do |file|
    rm file
  end
  rm "#{todir}/Rakefile"
  rm "#{todir}/.gitignore"
  download = "#{todir}/download"
  rm_rf download if File.exists?(download)
  mkdir download
  %w( *.gz *.deb *.rpm *.exe *.zip ).each do |glob|
    Dir["../products/#{glob}"].each do |file|
      cp file, download
    end
  end
  cp '../unix/lang/yabasic.htm', todir
  cp '../unix/lang/docbook.css', todir
end

desc 'Remove generated html-files'
task :remove => :copy do
  generated_html.each do |file|
    rm file
  end
end

desc 'Create and push new tag'
task :tag => :copy do
  if git_pending
    puts "\n\n**** Changes for git still pending (see above), will not create a new Tag ****\n\n"
    puts 'Press RETURN to continue: '
    gets
  else
    tags = %x{ git tag --list}.lines.map(&:chomp)
    new_tag = File.open('../yabasic.version').read
    if tags.include?(new_tag)
      puts "\nTag #{new_tag} is already present.\n"
    else
      puts "\nCreating new tag #{new_tag} with this message:"
      File.open('../tag-message').read.lines.each {|l| print ">  ",l}
      puts 'Press RETURN to continue: '
      gets
      sh "git tag -a #{new_tag} -F ../tag-message" do |ok,res|
        fail "Could not create tag: #{res}" unless ok
      end
    end
  end
end

desc 'Upload new files'
task :upload => :tag do
  puts "\nUploading html-files ..."
  puts "Please enter password for 2484.de@ftp.2484.de to continue   ** OR **   just hit RETURN to skip upload: "
  password = STDIN.noecho(&:gets).chomp
  if password.length == 0
    puts "\n\n**** Skipping upload ****\n\n"
  else
    ENV['CURLPW'] = password
    template = 'curl --insecure "ftp://ftp.2484.de/%s/" --user "2484.de:$CURLPW" --upload-file %s'
    
    puts 'Transfering files from products/web'
    Dir.chdir('../products/web') do
      files = %w{yabasic.htm docbook.css} + Dir['*.html']
      files.each do |file|
        puts file
        sh ( template % [ 'yabasic', file ] )
      end
      Dir.chdir('download') do
        puts "\n\nUploading binaries ..."
        puts 'Press RETURN to continue: '
        gets
        Dir['???*'].each do |file|
          puts file
          sh ( template % [ 'yabasic/download', file ] )
        end
      end
    end
  end
end

desc 'Invoke site'
task :browse => :upload do
  puts 'Starting adsf locally'
  system 'killall adsf'
  system 'cd ../products/web ; nohup adsf -p 3000 &'
  puts "\nBrowsing to http://www.yabasic.de and to adsf serving local files"
  puts "\n\nPress RETURN    ** TWICE **    to continue: \n\n"
  gets
  sh '"/mnt/c/Program Files/Mozilla Firefox/firefox.exe" localhost:3000 http://www.yabasic.de '
end

desc 'Push tag'
task :default => :browse do
  if git_pending
    puts "\n\n**** Changes for git still pending, no new tag has been created; cannot push it ****\n\n"
    puts 'Press RETURN to continue: '
    gets
  else
    puts "Press RETURN to push tag: "
    gets
    sh '/usr/bin/git push'
    sh '/usr/bin/git push --tags'
  end
  system 'killall adsf'
end
