#!/usr/bin/ruby
# Print the libpq environment (PGHOST, PGPORT, PGUSER, PGPASSWORD, PGDATABASE)
# for the main database of /etc/gitlab/database.yml to be evaluated by sh:
#   eval "$(/usr/lib/gitlab/gitlab-db-env)"
require 'yaml'
require 'shellwords'

file = ARGV[0] || '/etc/gitlab/database.yml'
env = ENV.fetch('RAILS_ENV', 'production')
config = YAML.safe_load_file(file, aliases: true)[env] || abort("#{file}: no #{env} section")
# GitLab 15.9+ uses the multiple databases layout: production: main: ...
config = config['main'] if config['main'].is_a?(Hash)

{ 'PGHOST' => 'host', 'PGPORT' => 'port', 'PGUSER' => 'username',
  'PGPASSWORD' => 'password', 'PGDATABASE' => 'database' }.each do |var, key|
  next if config[key].nil? || config[key].to_s.empty?

  puts "#{var}=#{config[key].to_s.shellescape}; export #{var}"
end
