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

require 'yaml'

#
# Allow access to our common-code.
#
$LOAD_PATH << '/usr/share/bytemark'
$LOAD_PATH << '../lib/bytemark' if ENV['TEST'] && ENV['TEST_PREFIX']

require 'healthcheck/command_output'


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 = Bytemark::Healthcheck::CommandWrapper.run_command('/usr/share/bytemark/healthcheck/get-ntp-offset')
  elsif File.executable?('../lib/bytemark/healthcheck/get-ntp-offset')
    diff = Bytemark::Healthcheck::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>We failed to parse the following as a float '#{diff}' - we got the error '#{ex.message}'.</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
