#! /usr/bin/env ruby
#
# Trema command-line tool.
#
# Author: Yasuhito Takamiya <yasuhito@gmail.com>
#
# Copyright (C) 2008-2012 NEC Corporation
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License, version 2, as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#


$LOAD_PATH.unshift File.expand_path( File.join File.dirname( __FILE__ ), "ruby" )


require "English"
require "fileutils"
require "trema/command"
require "trema/path"


def setup_tmp
  if FileTest.exist?( Trema.tmp ) and not FileTest.writable?( Trema.tmp )
    # Trema is system widely installed with gem command
    sh "sudo chmod o+w -R #{ Trema.tmp }"
  end

  FileUtils.mkdir_p Trema.log
  FileUtils.mkdir_p Trema.pid
  FileUtils.mkdir_p Trema.sock
end


def method_for command
  case command
    when "version", "-V", "--version"
      return :show_version
    when "ruby"
      return :ruby
    when "help", "-h", "--help", "/?", "-?"
      return :usage
  end

  setup_tmp

  case command
    when "run", "start"
      return :run
    when "up"
      return :up
    when "kill", "stop", "off", "down"
      return :kill
    when "killall"
      return :killall
    when "send_packets", "send_packet"
      return :send_packets
    when "show_stats"
      return :show_stats
    when "reset_stats"
      return :reset_stats
    when "dump_flows", "dump_flow"
      return :dump_flows
    when "shell", NilClass
      return :shell
    else
      return nil
  end
end


command = ARGV.shift
if method_for( command )
  begin
    include Trema::Command
    __send__ method_for( command )
  rescue
    $stderr.puts $ERROR_INFO.message
    $ERROR_INFO.backtrace.each do | each |
      $stderr.puts each if $verbose
    end
    exit false
  end
else
  $stderr.puts "Unknown command: '#{ command }'"
  $stderr.puts "Type '#{ $0 } --help' for usage."
  exit false
end


### Local variables:
### mode: Ruby
### coding: utf-8
### indent-tabs-mode: nil
### End: