#! /usr/bin/env ruby

require 'optparse'
require 'log_tools/converter.rb'

Orocos.initialize

#load all conversions
if ENV['ROCK_PREFIX']
    path = File.join(ENV['ROCK_PREFIX'],'log','migration') 
    require_dir path if File.directory? path
end

include LogTools

Converter.logger.level = Logger::INFO
converter = Converter.new
converter.post_fix = ""
converter.output_folder = "updated"
parser = OptionParser.new do |opt|
    opt.banner = <<-EOT

usage: rock-convert <log file>
    
    Updates log files containing base/types to the current version. 
    It can also be used to update log files containing custom types if 
    the conversion between the old and the new type is unambiguous 
    (field, enum value was added...).

    All files are stored by default in a subfolder called 'updated'.

Examples:
 rock-convert logfile.0.log 

    EOT

    opt.on('--help') do
        puts parser
        exit 0
    end
    opt.on('-p', '--postfix POSTFIX', 'Postfix which is added to the input file name to produce the output file name.') do |p|
        converter.post_fix = p
    end

    opt.on('-o', '--output OUTPUT', 'Output folder where the converterted log files are saved.') do |o|
        converter.output_folder = o
    end

    opt.on('-s', '--streams STREAMS', Array, 'Stream names which shall be converted. If not given all streams are selected') do |s|
        converter.streams = s
    end

    opt.on('--from TIME', 'Ignores all samples which were recorded before the given time (yyyy/mm/dd hh:mm:ss)') do |from|
        if from =~ /(....)\/(..)\/(..) (..)\:(..)\:(..)/
          converter.from = Time.local($1,$2,$3,$4,$5,$6)
          puts converter.from
        else
          raise "Time format from is wrong"
        end
    end

    opt.on('--to TIME', 'Ignores all samples which were recorded after the given time (yyyy/mm/dd hh:mm:ss)') do |to|
        if to =~ /(....)\/(..)\/(..) (..)\:(..)\:(..)/
          converter.to = Time.local($1,$2,$3,$4,$5,$6)
        else
          raise "Time format to is wrong"
        end
    end

    opt.on('--use_sample_time[=FIELD]', String, 'Uses the \'time\' field of the sample (if present) as timestamp of the data sample in the log file') do |fieldname|
        Converter.warn "--use_sample_time is deprecated. Use --use-sample-time instead"
        converter.use_sample_time = (fieldname || :time).to_sym
    end
    opt.on('--use-sample-time[=FIELD]', String, 'Uses the \'time\' field of the sample (if present) as timestamp of the data sample in the log file') do |fieldname|
        converter.use_sample_time = (fieldname || :time).to_sym
    end

    opt.on('--time-offset SECONDS', String, 'Number of seconds the log time is shifted') do |seconds|
        converter.time_offset = seconds.to_f
    end

    opt.on('--converter FILE', String, 'Optional ruby file defining custom conversion') do |file|
        begin
            require File.expand_path(file)
            converter.reload_converter
        rescue Exception => e
            LogTools.warn "Cannot register converter #{file}: #{e}."
        end
        # EXAMPLE:
        #    LogTools::Converter.register "converter for base type sonar scan", Time.now,Orocos.registry do
        #        conversion "/base/samples/SonarScan","/base/samples/SonarBeam" do |dst,src|
        #            deep_cast(dst,src)
        #        end
        #     end
    end

    opt.on('--keep-registry', 'keeps the logfile registry and does not update the samples to the current one') do
        converter.keep_registry = true
    end

    opt.on('--debug') do
        Converter.logger.level = Logger::DEBUG
        LogTools.logger.level = Logger::DEBUG
    end
end

remaining = parser.parse(ARGV)
if remaining.empty?
    puts parser
    exit(1)
end

begin
    time = Time.now
    converter.convert remaining
    puts 
    puts "all done in #{Time.now-time} seconds!"
    puts 
rescue Interrupt
    puts
    puts "Interrupted"
    puts
end
