#!/usr/bin/ruby
#
require 'time'

usage = <<US
slice-trace <trace table> <start date> <end date>
Example: slice-trace ABCD_20090201 2009-2-1-09:45 10:45
Will create ABCD_20090201s09451045_Flows from ABCD_20090201_Flows including all
the flows existing in the specified time interval. The included flows are those
that start after start date and die before end date. Use -c to include the flows
that start before start date and die after end date.
Options:
-c      include flows whose life span cover the specified time interval
US

cf = false
if ARGV[0] == '-c'
    cf = true
    ARGV.shift
end
trace = ARGV[0] || abort('Expecting trace table name: ' + usage)
start_date = ARGV[1] || abort("Expecting start_date: " + usage);
end_date = ARGV[2] || abort("Expecting end_date: " + usage);

def parse_time(s, start)
  if s =~ /^(\d+)(\.\d+)?$/
    return Time.at(s.to_f)
  else
    return Time.parse(s, start)
  end
end

start_date = parse_time(start_date, nil)
end_date = parse_time(end_date, start_date)

use_day = start_date.day != end_date.day

if use_day
  id = "%02d%02d%02d%02d%02d%02d" % [start_date.day, start_date.hour,
    start_date.min, end_date.day, end_date.hour, end_date.min]
else
  id = "%02d%02d%02d%02d" % [start_date.hour, start_date.min,
    end_date.hour, end_date.min]
end

newtrace = "#{trace}s#{id}"

$stderr.puts "slice-trace 0.1"
$stderr.puts "new trace: " + newtrace
$stderr.puts "from: " + start_date.to_s
$stderr.puts "to: " + end_date.to_s

sql = <<SQL
SELECT COUNT(*) FROM `#{trace}_Flows`;

CREATE TABLE `#{newtrace}_Flows` LIKE `#{trace}_Flows`;

INSERT INTO `#{newtrace}_Flows`
SELECT * FROM `#{trace}_Flows` WHERE
(`FirstPktTs` >= #{start_date.to_f} AND `FirstPktTs` < #{end_date.to_f})
SQL
if cf == true
    sql += " OR (`FirstPktTs` < #{start_date.to_f} AND `LastPktTs` >= #{start_date.to_f})"
end
sql += ";\n"
sql += <<SQL
INSERT INTO `Traces` (`Name`, `Description`, `StartDate`, `EndDate`, `DataPath`)
SELECT '#{newtrace}', CONCAT('Slice of ', Description),
FROM_UNIXTIME(#{start_date.to_i}), FROM_UNIXTIME(#{end_date.to_i}), DataPath FROM Traces
WHERE Name = '#{trace}';

ALTER TABLE `Traces` ORDER BY `Name`;
SQL

puts sql
