#!/usr/bin/env ruby-bleak-house
# Script to launch thin with Bleak House
# http://blog.evanweaver.com/files/doc/fauna/bleak_house/files/README.html
# 
# Will dump data to log/memlog
# Analyze the dump w/:
# 
#  bleak log/memlog
# 

module Kernel
  def alias_method_chain(target, feature)
    # Strip out punctuation on predicates or bang methods since
    # e.g. target?_without_feature is not a valid method name.
    aliased_target, punctuation = target.to_s.sub(/([?!=])$/, ''), $1
    yield(aliased_target, punctuation) if block_given?
    
    with_method, without_method = "#{aliased_target}_with_#{feature}#{punctuation}", "#{aliased_target}_without_#{feature}#{punctuation}"
    
    alias_method without_method, target
    alias_method target, with_method
    
    case
      when public_method_defined?(without_method)
        public target
      when protected_method_defined?(without_method)
        protected target
      when private_method_defined?(without_method)
        private target
    end
  end
end

module BleakInstruments
  module Connection
    def self.included(base)
      base.class_eval do
        alias_method_chain :receive_data, :instrument
        alias_method_chain :process, :instrument
      end
    end
    
    def receive_data_with_instrument(data)
      receive_data_without_instrument(data)
      $memlogger.snapshot($logfile, "connection/receive_data", false, 0.1)
    end
    
    def process_with_instrument
      process_without_instrument
      $memlogger.snapshot($logfile, "connection/process", false, 0.1)
    end
  end
  
  module Backend
    def self.included(base)
      base.class_eval do
        alias_method_chain :connect, :instrument
        alias_method_chain :initialize_connection, :instrument
      end
    end
    
    def connect_with_instrument
      connect_without_instrument
      $memlogger.snapshot($logfile, "backend/connect", false, 0.1)
    end
    
    def initialize_connection_with_instrument(connection)
      initialize_connection_without_instrument(connection)
      $memlogger.snapshot($logfile, "backend/initialize_connection", false, 0.1)
    end
  end
end

require 'rubygems'
require 'bleak_house'

$: << File.join(File.dirname(__FILE__), '..', 'lib')
require 'thin'

Thin::Connection.send :include, BleakInstruments::Connection
Thin::Backends::TcpServer.send :include, BleakInstruments::Backend

$memlogger = BleakHouse::Logger.new
File.delete($logfile = File.expand_path("log/memlog")) rescue nil

load 'bin/thin'
