penguin/utils

my env utils

bash/sources/15_gpg-agent

raw ยท 1355 bytes

#!/bin/bash

function rbash-gpg-agent-enable-ssh {
	local _gnupg_home _conf _changed

	_gnupg_home="${GNUPGHOME:-$HOME/.gnupg}"
	_conf="$_gnupg_home/gpg-agent.conf"
	_changed=

	mkdir -p "$_gnupg_home" || return 1
	chmod 700 "$_gnupg_home" 2>/dev/null || true

	touch "$_conf" || return 1
	chmod 600 "$_conf" 2>/dev/null || true

	if ! grep -Eq '^[[:space:]]*enable-ssh-support([[:space:]]|$)' "$_conf"; then
		printf "\n%s\n" "enable-ssh-support" >> "$_conf"
		_changed=yes
	fi

	if [ -n "$_changed" ]; then
		gpgconf --kill gpg-agent >/dev/null 2>&1 || true
	fi

	gpg-connect-agent /bye >/dev/null 2>&1 || true
}

_rbash_gpg_enabled=

if command -v gpg-connect-agent >/dev/null 2>&1; then
	export GPG_TTY
	GPG_TTY="$(tty 2>/dev/null || true)"

	gpg-connect-agent /bye >/dev/null 2>&1 || true

	if [ -n "$GPG_TTY" ]; then
		gpg-connect-agent updatestartuptty /bye >/dev/null 2>&1 || true
	fi

	_rbash_gpg_enabled=yes
fi

if command -v gpgconf >/dev/null 2>&1 &&
	[ -f "${GNUPGHOME:-$HOME/.gnupg}/gpg-agent.conf" ] &&
	grep -Eq '^[[:space:]]*enable-ssh-support([[:space:]]|$)' "${GNUPGHOME:-$HOME/.gnupg}/gpg-agent.conf"
then
	_rbash_gpg_ssh_sock="$(gpgconf --list-dirs agent-ssh-socket 2>/dev/null || true)"

	if [ -n "$_rbash_gpg_ssh_sock" ]; then
		export SSH_AUTH_SOCK="$_rbash_gpg_ssh_sock"
	fi

	_rbash_gpg_enabled=yes
	unset _rbash_gpg_ssh_sock
fi