#!/usr/bin/env ruby

#################
## NSM Console ##
## Version 0.2 ##
#################

## The following variables will ALWAYS be replaced:
## ${PCAP_FILE} - The pcap datafile
## ${PCAP_BASE} - The basename of the pcap datafile
## ${MODULE_DIR} - The base module directory (modules)
## ${MODULE_NAME} - The base name (without the .module) of the module
## ${OUTPUT_DIR} - The base output directory

## Require nsm console specific files
require 'lib/command_manager'
require 'lib/commands'
require 'lib/logging'
require 'lib/nsm_module'
require 'lib/nsm_category'
require 'lib/nsm_helper'

## Require other ruby files
require 'readline'
include Readline

## Required for tab completion
$tabstrings = CommandManager.get_commands_as_array()
Readline.completion_proc = lambda{|s| $tabstrings.find_all{|elm| elm =~ /#{s}/}}

## Default module directory
$moduledir = "modules"
## Default output directory
$outputdir = "output"

$modules = []
$categories = []
$datafile = ""
$basefile = ""

###################
## Begin program ##
###################

## Print the lobster
print_banner()

## Set {$PCAP_FILE} if passed in as an argument
CommandManager.execute("file",ARGV[0]) if ARGV.length > 0

## Load modules
load_modules($moduledir)
load_categories($moduledir)

## Initialize logging
logfilename = "logs/nsm-log."
logfilename.concat(Time.now.year.to_s)
logfilename.concat(Time.now.month.to_s)
logfilename.concat(Time.now.day.to_s)
## Uncomment for more log file granularity
#logfilename.concat(Time.now.min.to_s)
#logfilename.concat(Time.now.sec.to_s)
logfilename.concat(".log")
puts "Logging to #{logfilename}\n\n"
Logger.new(logfilename)
## Write initial entry
Logger.write("-" * 80)
Logger.write("\n")
Logger.write("Log for nsm-console begun at #{Time.now.year}-#{Time.now.month}-#{Time.now.day} #{Time.now.hour}:#{Time.now.min}:#{Time.now.sec}\n")
Logger.write("-" * 80)
Logger.write("\n")

puts "Default ${OUTPUT_DIR} is '#{$outputdir}'"
puts "Default ${MODULE_DIR} is '#{$moduledir}'"

cmd = ""

print "\n"
puts "=-" * 35
puts "Welcome to NSM Console, type 'help' to see available commands"
puts "=-" * 35
puts "Note: All modules are DISABLED by default, use 'list' to list available"
puts "modules and 'toggle <module>' to disable/enable a module.\n\n"

## Command loop until quit
while (true)
  
  ## New method uses readline so we can use tab-completion
  cmd = readline("nsm> ", TRUE)

  ## Split the command into function and arguments
  unless cmd.nil?
    cmd.gsub!(/(\w)\s(.*)/) { $1 }
    cmd.chomp!
    args = $2
  
    begin
      CommandManager.execute(cmd,args) unless cmd.length < 1
    rescue LocalJumpError
      ## Ignore LocalJumpErrors, it just means we returned
    #rescue 
    #  puts "Command '#{cmd}' unrecognized. Try 'help' for a list of commands."
    end
  end

end
