#!/usr/bin/ruby

require 'symbiosis/monitor/check'

# Check that the SSH service is running and responding on TCP
class SshdCheck < Symbiosis::Monitor::Check
  def initialize(connections)
    super pid_file: '/var/run/sshd.pid',
          init_script: '/etc/init.d/ssh',
          unit_name: 'ssh',
          process_name: 'sshd',
          connections: connections
  end

  def do_tcpresponse_check(responses)
    raise "Unexpected response '#{responses.first}'" unless responses.first =~ /^SSH/
  end
end

sshd_config = '/etc/ssh/sshd_config'
port = host = nil

if File.exist? sshd_config
  File.readlines(sshd_config).each do |l|
    case l.chomp
      # ListenAddress [host|IPv6_addr]:port
      # ListenAddress host|IPv4_addr:port
      # ListenAddress host|IPv4_addr
    when /^\s*ListenAddress\s+(.*)(?::(\d+))?\s*$/i
      if host.nil? && port.nil?
        host = Regexp.last_match(1)
        port = Regexp.last_match(2).to_i
      end

      # Port port
    when /^\s*Port\s+(\d+)\s*$/i
      port = Regexp.last_match(1).to_i if port.nil?

    end
  end
end

host = Regexp.last_match(1) if host =~ /\[(.*)\]/
#
# Set some defaults.
#
host ||= 'localhost'
port ||= 22

connections = [
  Symbiosis::Monitor::TCPConnection.new(host, port, [nil, 'SSH-2.0-OpenSSH-5.5p1\n'])
]

exit SshdCheck.new(connections).do_check if $PROGRAM_NAME == __FILE__
