######################### rover_utils.rb achase@mbari.org ###################### 
#
# Common utilities
#
################################################################################

# A module for standardized logging
module LogHelper
  @@datalog_dir = '/cf/rover/datalog/'
  @@syslog_dir = '/cf/rover/syslog/'

  def datalog message
    t = Time.now
    filename = t.strftime("#{@@datalog_dir}#{self.class.name}%Y%m%d.log")
    File.open(filename, "a") do |file|
      file.puts t.strftime("%Y%m%d%H%M%S : ") << message
    end 
  end
  
  def syslog message
    t = Time.now
    filename = t.strftime("#{@@syslog_dir}%Y%m%d.log")
    File.open(filename, "a") do |file|
      file.puts t.to_s << " : #{self.class.name} : " << message
    end
  end

  def LogHelper.syslog message
    t = Time.now
    filename = t.strftime("#{@@syslog_dir}%Y%m%d.log")
    File.open(filename, "a") do |file|
      file.puts t.to_s << ": " << message
    end
  end

  def LogHelper.datalog_dir= dir
    LogHelper.change_dir(dir) {|new_dir| @@datalog_dir = new_dir }
  end

  def LogHelper.syslog_dir= dir
    LogHelper.change_dir(dir) {|new_dir| @@syslog_dir = new_dir }
  end
  
  #change the directory currently beined used to log data to the directory
  #specified. This methods expects a block, which it will call if the 
  #new directory exists or is successfully created. In the block you should
  #set the variable that is changed to the new directory name
  def LogHelper.change_dir dir
    dir = dir + "/" unless dir[-1] == "/"[0]
    if LogHelper.make_dir_if_needed dir
      yield dir
    end
  end 
  
  #if the directory does not exist, and no file exists with the same name a
  #new directory will be made.
  #true returned if directory now exists
  #false returned if directory was unable to be created
  def LogHelper.make_dir_if_needed dir
    #when checking for a file, remove the trailing '/', [0..2] will give this
    unless File.directory?(dir) || File.exists?(dir[0..-2])
      Dir.mkdir(dir)
    end
    if File.directory?(dir)
      true
    elsif
      false
    end
  end
end

