#!/usr/bin/env ruby
#
#   Rip apart the Scala Pleac code into a
#    newly named, daystamped directory.
#    Go there, and try to scala-compile
#    all of the scala files there.
#

# This script adds surroundings to get each
#  section to compile.

def stamp

    tdfd = IO.popen("tdc_sh")
    tdstamp = tdfd.readlines[ 0 ].chomp

    # If you want a full timestamp, just return tdstamp.
    # tdstamp.sub /_.*/, ''
    tdstamp
end

def dname
    'src-' + stamp
end

class Line_collector
    def initialize
	@lines = [ ]
    end
    def << line
	if @lines.length == 0  and  line =~ /@@SKIP@@/
	    @skipit = true
	end
	@lines << line
    end
end

class PLEAC_Section < Line_collector
    def initialize iDir, iLine
	@dir_name = iDir
	@suffix = iLine.sub /.*@@PLEAC@@_/, ''
	@skipit = false
	super()
    end

    def go_for_it
	return if @skipit
	puts "go for it section #@suffix:"
	puts " ( #{@lines.length} lines. )"

	exeFnm = "#@dir_name/section_#@suffix"
	srcFnm = "#{exeFnm}.scala"

	idsuff = @suffix.gsub /\./, '_'

	File.open( "#{srcFnm}", 'w' ) do |fd|
		# Wrap an object decl, and a "main" function around it:
		fd.puts <<-EOHDR
		    package us.l6r.pleac
		    object test_section_#@idsuff {
		       def main ( args : Array[String] ) = {
		EOHDR

		# Extract this section's scala code
		@lines.each {|ln| fd.puts ln }

		# End the wrapper object-and-main decl
		fd.puts "   Console.println( \"Done with section #@suffix.\" )"
		fd.puts "   }\n}"
	    end

	# scalac it.
	system "echo scalac #{srcFnm}"
	res = system "scalac #{srcFnm}"
	if not res
	    puts "\"scalac #{srcFnm}\" failed, err code #{$?}." 
	    return false
	end

	# run that
	system "scala #{exeFnm}"
    end
end

class PLEAC_Name < Line_collector
    def go_for_it
	puts 'NAME ... ', @lines
	true
    end
end
class PLEAC_Web < Line_collector
    def go_for_it
	puts 'WEB ... ', @lines
	true
    end
end

def flush scn
    if scn
	scn.go_for_it
    else
	true
    end
end

def rip_it fnm
    out_dir = dname
    Dir.mkdir out_dir
    fd = File.open( fnm ).readlines
    cur_scn = nil
    fd.each do |line|
	    case line.chomp!
	     when /@@PLEAC@@_NAME/
		break unless flush cur_scn
		cur_scn = PLEAC_Name.new
	     when /@@PLEAC@@_WEB/
		break unless flush cur_scn
		cur_scn = PLEAC_Web.new
	     when /@@PLEAC@@/
		break unless flush cur_scn
		cur_scn = PLEAC_Section.new out_dir, line
	     else
		if cur_scn
		    cur_scn << line
		else
		    puts "No current section;     \"#{line}\" "
		end
	    end
	end

end

rip_it 'pleac_scala.data'

