#!/usr/bin/ruby1.8
#
# Copyright (c) 2011 Polytechnic Institute of New York University
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
# Contact: ffund01@students.poly.edu



require "/usr/bin/oml4r.rb"

APPNAME = "wmxstat"
APPPATH = "/usr/bin/wimaxcu"
APPVERSION = "1.2"

class MPStat < OML4R::MPBase
    name :status_link
    param :freq, :type => :long
    param :signal
    param :rssi, :type => :long
    param :cinr, :type => :long
end

class Wrapper

  def process(output)
    lines = output.split("\n")
    lines=lines.drop(1)
    lines=lines.reverse.drop(2).reverse
    vals=lines.collect { |row|
      column = row.split(" ")
      column[2]
    }

    # Inject the measurements into OML 
    MPStat.inject(vals[0],vals[1],vals[2],vals[3])
  end

  def initialize(args)
    
    # Initialize variables 
    @interval = 5

    # Initialize OML4R
    OML4R::init(args, :appID => APPNAME) 

  end
    
  def start()
    while true
      # Run 'wimaxcu scan'; capture its output and process it 
      cmd = "#{APPPATH} status link"
      output = `#{cmd}`
      process(output)
      # Wait for a given duration and loop again
      sleep @interval.to_i
    end
  end

end

begin
  app = Wrapper.new(ARGV)
  app.start()
rescue Exception => ex
  puts "Received an Exception when executing the wrapper!"
  puts "The Exception is: #{ex}\n"
end

