#!/usr/bin/env ruby
# frozen_string_literal: true

# Project internal
require 'chronoleak'

if __FILE__ == $PROGRAM_NAME
  log = ChronoLeak::TermLog.new
  if ARGV.size == 1 && !['-h', '--help'].include?(ARGV.first)
    ip_addr = ARGV.first
    hping = "sudo hping3 #{ip_addr} --icmp --icmp-ts -c 1"
    out = ''
    Open3.popen3(hping) do |_stdin, stdout, stderr, _thread|
      out = stdout.read
      err = stderr.read
      if /hping3: command not found/.match?(err)
        log.fatal "hping not installed - 'hping3' command must be accessible in PATH"
        log.fatal 'See the package for your distro on https://repology.org/project/hping/versions.'
        raise(StandardError, "Command failed: #{hping}")
      elsif /100% packet loss/.match?(err)
        log.fatal 'ICMP timestamp requests (13) or ICMP timestamp replies (14) filtered.'
        raise(StandardError, 'hping command executed successfully but received no response.')
      end
    end
    timestamp_ms = out.match(/Transmit=(?<timestamp>\d+)/)[:timestamp].to_i
    puts ChronoLeak.display_times(timestamp_ms)
  else
    puts "#{__FILE__} <IP_address_or_domain>"
    puts
    puts "Version: #{ChronoLeak::VERSION} - ICMP Timestamp Remote Time Leaker"
    puts
    puts 'Nessus - ICMP Timestamp Request Remote Date Disclosure - https://www.tenable.com/plugins/nessus/10114'
    puts 'CVE-1999-0524 - https://www.tenable.com/cve/CVE-1999-0524'
  end
  log.close
end
