resource_name :postgresql_custom_server
provides :postgresql_custom_server

property :postgresql_version, String, required: true, name_property: true
property :role, String, required: true # Can be primary or replica

action :create do
  postgresql_version = new_resource.postgresql_version
  postgresql_data_dir = "/var/lib/postgresql/#{postgresql_version}/main"
  postgresql_service = "postgresql@#{postgresql_version}-main"
  postgresql_credentials = data_bag_item('credentials', 'postgresql')

  build_essential do
    compile_time true
  end

  package("libpq-dev") { action :nothing }.run_action(:install)

  chef_gem 'pg' do
    compile_time true
  end

  user "postgres" do
    manage_home false
  end

  postgresql_server_install "main" do
    version postgresql_version
    setup_repo true
    password postgresql_credentials['server_password']
    action :install
  end

  service postgresql_service do
    supports restart: true, status: true, reload: true
    action [:enable, :start]
  end

  # This service is a dependency that will auto-start our cluster service on
  # boot if it's enabled, so we disable it explicitly
  service "postgresql" do
    action :disable
  end

  shared_buffers = if node['memory']['total'].to_i / 1024 < 1024 # < 1GB RAM
                     "128MB"
                   else # >= 1GB RAM, use 50% of total RAM
                     "#{node['memory']['total'].to_i / 1024 / 2}MB"
                   end

  additional_config = {
    max_connections: 200, # default
    shared_buffers: shared_buffers,
    unix_socket_directories: "/var/run/postgresql",
    dynamic_shared_memory_type: "posix",
    timezone: "UTC", # default is GMT
    listen_addresses: "0.0.0.0"
  }

  additional_config[:promote_trigger_file] = "#{postgresql_data_dir}/failover.trigger"

  postgresql_server_conf "main" do
    version postgresql_version
    additional_config additional_config
    notifies :reload, "service[#{postgresql_service}]", :delayed
  end

  postgresql_user "replication" do
    action :create
    replication true
    password postgresql_credentials['replication_password']
  end
end

action_class do
  # to use the data_dir helper
  include PostgresqlCookbook::Helpers
end
