#!/usr/bin/ruby
#
# Ensure that our clock is "current".
#

require 'yaml'

$LOAD_PATH << '../lib/'

#
#  This class either a) returns the output of running commands, or
# b) returns the output from a faked command
#
class CommandWrapper
  def self.run_command(str)
    if ENV['TEST'] && ENV['TEST_PREFIX']
      #
      #  Count the number of commands we've executed so far.
      #
      count = ENV['TEST_COUNT'] || '0'
      count = count.to_i
      ENV['TEST_COUNT'] = (count + 1).to_s

      #
      #  Read the output from the faked file.
      #
      #    $prefix/$count.cmd
      #
      file = "#{ENV['TEST_PREFIX']}/#{count}.cmd"
      File.open(file, 'r').readlines.join
    else
      `#{str}`
    end
  end
end

if __FILE__ == $PROGRAM_NAME

  def verbose(str)
    STDERR.puts(str)
  end

  #
  # Alert(s) to raise
  #
  to_raise = []

  #
  # The difference
  #
  if File.executable?('/usr/share/bytemark/healthcheck/get-ntp-offset')
    diff = CommandWrapper.run_command('/usr/share/bytemark/healthcheck/get-ntp-offset')
  elsif File.executable?('../lib/bytemark/healthcheck/get-ntp-offset')
    diff = CommandWrapper.run_command('../lib/bytemark/healthcheck/get-ntp-offset')
  else
    h = {}
    h[:id]      = 'ntp-clock-low'
    h[:summary] = 'Failed to find get-ntp-offset.'
    h[:detail]  = '<p>The ntp-check is broken, or failing.</p>'
    to_raise.push(h)
    puts YAML.dump(to_raise)
    exit(0)
  end

  #
  # We should expect to receive the number of seconds difference.
  # explicitly convert that to a float - NOTE: Not an integer.
  #
  begin
    diff = Float(diff).abs
  rescue ArgumentError => ex
    h = {}
    h[:id]      = 'ntp-clock-low'
    h[:summary] = 'Failed to parse \'get-ntp-offset\' output.'
    h[:detail]  = '<p>The ntp-check is broken, or failing.</p>'
    to_raise.push(h)
    puts YAML.dump(to_raise)
    exit(0)
  end

  #
  # Show that.
  #
  verbose("Difference is #{diff}")

  if diff >= 5.0
    h = {}
    h[:id]      = 'ntp-clock-low'
    h[:summary] = 'The system-clock is out of sync with our remote NTP server(s).'
    h[:detail]  = "<p>The local time on this system is #{diff} seconds off that provided by pool.ntp.org</p>"
    to_raise.push(h)
  end

  # Show the output.
  puts YAML.dump(to_raise)
  exit(0)
end
