#!/usr/bin/env ruby

def putd(s)
  puts(s)
end

def putw(s)
  puts("WARNING: #{s}")
end

def pute(s)
  $stderr.puts(s)
end

class InvalidXfer < Exception
end

class Xfer
  attr_reader :port, :range
  def initialize(port, range)
    @port = port
    @range = range
    if range[0] >= range[1]
      putw("invalid range: #{range[0]}-#{range[1]} (port #{port})")
      raise InvalidXfer.new("teh fuck")
    end
  end
  def to_s
    "XFER(#{@port}): #{@range[0]}-#{@range[1]} size: #{size}"
  end
  def data
    return @d unless !@d
    File.open("#{port}.txt", "rb") { |f|
      s = f.read(100000)
      @d = s.partition("\r\n\r\n")[2][0, size]
    }
    @d
  end
private
  def size
    @range[1] - @range[0] + 1
  end
end

def check_range_overlaps(xfers)
  prev = nil
  xfers.each { |xf|
    next unless prev
    if xf.range[0] <= prev.range[1]
      putw("overlap: #{xf.range[0]}-#{prev.range[1]} " +
           "(ports: #{xf.port}, #{prev.port})")
    end
  }
end

xfers = []
port=0
while l = $stdin.gets
  md = /^T 127.0.0.1:(\d+)/.match(l)
  if md
    port = md[1].to_i
    next
  end
  md = /^Range: bytes=(\d+)-(\d+)/.match(l)
  if md
    raise "wtf" unless port != 0
    begin
      xfers << Xfer.new(port, [md[1].to_i, md[2].to_i])
    rescue InvalidXfer => e
      putw("ignoring connection from port #{port}")
    end
    port = 0
  else
    raise "unknown line: #{l}"
  end
end

xfers.sort! { |a, b|
  a.range[0] <=> b.range[0]
}

puts("got #{xfers.size} valid ranges")
check_range_overlaps(xfers)

xfers.each { |xfer|
  puts(xfer)
}

File.open("key.jpg", "wb") { |o|
  xfers.each { |xfer|
    o.write(xfer.data)
    putd("wrote #{xfer.data.size} bytes")
  }
}
