#!/usr/bin/env bash

# Print the stable id of one existing Certbot account. Hosts may contain more
# than one registered account; non-interactive Certbot otherwise stops to ask
# which account should authorize a new certificate.
select_certbot_account() {
  local accounts_dir="${1:-/etc/letsencrypt/accounts}"
  local server_dir="$accounts_dir/acme-v02.api.letsencrypt.org/directory"
  local registration

  registration="$(
    find "$server_dir" -type f -name regr.json -print 2>/dev/null \
      | LC_ALL=C sort \
      | head -1
  )"
  [ -n "$registration" ] || return 0
  basename "$(dirname "$registration")"
}
