# -*- coding: binary -*-

#
# XXX: This is a VERY ROUGH mixin for Expect-style interaction
#

require 'expect'

module Msf::Exploit::Remote::Expect

  # Send a line and expect a pattern
  #
  # @param line [String] Line to send
  # @param pattern [Regexp] Pattern to expect
  # @param sock [Socket] Socket to send/expect on
  # @param newline [String] Newline character(s)
  # @param timeout [Float] Seconds to expect pattern
  # @return [void]
  def send_expect(line, pattern, sock:, newline: "\n", timeout: 3.5)
    unless sock.respond_to?(:put) && sock.respond_to?(:expect)
      raise ArgumentError, 'sock does not appear to be a socket'
    end

    if line
      print_status("Sending: #{line}")
      sock.put("#{line}#{newline}")
    end

    return unless pattern

    print_status("Expecting: #{pattern.inspect}")
    sock.expect(pattern, timeout) do |res|
      unless res
        raise Timeout::Error, "Pattern not found: #{pattern.inspect}"
      end

      vprint_good("Received: #{res.first}")
    end
  end

end
