rs_tools 'rightscale_lbtools-0.13.6.tgz'

package 'haproxy' do
  action :install
end

service 'haproxy' do
  supports(:restart => true, :reload => true)
  action [:enable]
end

directory '/home/haproxy' do
  owner     'haproxy'
  group     'haproxy'
  mode      '0755'
  recursive true
  action    :create
end

template '/etc/default/haproxy' do
  source 'default_haproxy.erb'
  owner  'root'
  notifies(:restart, resources(:service => 'haproxy'))
end

stats_uri        = "#{node.lb_haproxy[:haproxy_stats_uri]}"
stats_user       = "#{node.lb_haproxy[:haproxy_stats_user]}"
stats_password   = "#{node.lb_haproxy[:haproxy_stats_password]}"
health_check_uri = "#{node.lb_haproxy[:health_check_uri]}"

stats_uri_line  = "stats uri #{stats_uri}"
stats_auth_line = "stats auth #{stats_user}:#{stats_password}"
health_check_uri_line =
  "option httpchk GET #{health_check_uri} HTTP/1.1\\r\\nHost:\\ localhost"

template node.lb_haproxy[:cfg_file] do
  source 'haproxy_http.erb'
  owner  'haproxy'
  group  'haproxy'
  mode   '0400'

  variables({
    :stats_uri_line        => stats_uri_line,
    :stats_auth_line       => stats_auth_line,
    :health_check_uri_line => health_check_uri_line,
    :errors_dir            => "#{node.app[:frontend_root]}/errors",
    :applistener_name      => node.lb_haproxy[:applistener_name],
    :bind_address          => node.lb_haproxy[:bind_address],
    :bind_port             => node.lb_haproxy[:bind_port]
  })

  notifies(:restart, resources(:service => 'haproxy'))
end

right_link_tag "loadbalancer:lb=#{node.lb_haproxy[:applistener_name]}"

log 'RightScale LB installation and configuration complete'