#!/usr/bin/env ruby
require "optparse"

filename="./etc/dcast.conf"
start_line=""
end_line=""
str = Array.new
argv_num = ARGV.length

# output "host", "ip", "mac" of slave nodes.
def output_slave(start_line, end_line, filename)
  slave = Array.new
  open(filename, "r"){|io|
    i = 0
    while line = io.gets
      i = i + 1
      if start_line < i && end_line > i
        slave.push(line) unless line =~ /^#/
      end
    end
  }
  return slave
end

open(filename, "r"){|io|
  i = 0
  while line = io.gets
    i = i + 1
    if line =~ /^### SLAVE CONFIG ###/
        start_line = i
    end
    if line =~ /^### END OF FILE ###/
      end_line = i
    end
  end
}

parser = OptionParser.new
parser.banner = "Usage: #{File.basename($0)} [host] [ip] [mac]"

parser.on("--host", "slave names."){|arg|
  output_slave(start_line, end_line, filename).each{|a|
    str.push(a.split[0])
  }
}
parser.on("--ip", "slave ip addresses."){|arg|
  output_slave(start_line, end_line, filename).each{|a|
    str.push(a.split[1])
  }
}
parser.on("--mac", "slave mac addresses."){|arg|
  output_slave(start_line, end_line, filename).each{|a|
    str.push(a.split[2])
  }
}
parser.on("--help", "-h", "Print this message and quit."){
  puts "set: --help"
  puts parser.help
  exit 0
}

#############################
# main
#############################
begin
  parser.parse!
  if argv_num == 0
    system("./" + File.basename($0) + " -h")
    exit 1
  end
  line = (str.length / argv_num)
  case argv_num
  when 1
    line.times{|i|
      puts str[i]
    }
  when 2
    line.times{|i|
      puts str[i] + "\t"+ str[i+line]
    }
  when 3
    line.times{|i|
      puts str[i] + "\t"+ str[i+line] + "\t"+ str[i+line+line]
    }
  else
    system("./" + File.basename($0) + " -h")
    exit 1
  end

rescue OptionParser::ParseError => err
  $stderr.puts err.message
# $stderr.puts parser.help
  exit 1
end
