#!/usr/bin/ruby

require 'symbiosis/monitor/check'
require 'English'

# ensure service is running and responds to pings
class MysqldCheck < Symbiosis::Monitor::Check
	DEBIAN_CONFIG_PATH = '/etc/mysql/debian.cnf'.freeze
  def initialize
    super pid_file: '/var/run/mysqld/mysqld.pid',
          init_script: '/etc/init.d/mysql',
          unit_name: 'mysqld'
  end

  def config_readable?
    unless File.readable?(DEBIAN_CONFIG_PATH)
      puts "Unable to test connection, as #{DEBIAN_CONFIG_PATH} is not readable"
      return SystemExit::EX_NOPERM
    end
    SystemExit::EX_OK
  end

  def ping_check
    puts 'Testing connection with a ping'
    cmd = "/usr/bin/mysqladmin --defaults-extra-file=#{DEBIAN_CONFIG_PATH} ping 2>&1"
    Kernel.system(cmd)
    if $CHILD_STATUS.success?
      puts 'Connection tested OK.'
      return SystemExit::EX_OK
    else
      puts 'Connection test failed.'
      restart
      return SystemExit::EX_TEMPFAIL
    end
  end

  def do_check
    r = super
    puts "Trying to ping mysql"
    return r unless SystemExit::EX_OK == r
    return SystemExit::EX_CONFIG unless File.executable?('/usr/bin/mysqladmin')

    r = config_readable?
    return r unless SystemExit::EX_OK == r

    return ping_check
  rescue => err
    puts "Connection test errored - #{err}"
    return SystemExit::EX_UNAVAILABLE
  end
end

exit MysqldCheck.new.do_check if $PROGRAM_NAME == __FILE__
