#!/bin/bash
#
# This is a wrapper script around ssh-agent to prevent special variables
# (LD_LIBRARY_PATH, etc.) from being unset due to ssh-agent being setgid.
#
# Author: Anders Kaseorg <anders@kaseorg.com>
#

# Skip the ssh-agent options that aren't the command.
declare -a ssh_agent_args='()'
while true; do
    case "$1" in
    --)				shift; break ;;
    -[at] | -[^at]*[at])	ssh_agent_args+=("$1" "$2"); shift ;;
    -*)				ssh_agent_args+=("$1"); shift ;;
    *)				break ;;
    esac
done

# If there's a command, preserve the environment variables clobbered by setgid
# programs (as listed in glibc-2.3.6/sysdeps/generic/unsecvars.h).
if [ $# -ne 0 ]; then
    ssh_agent_args+=("/usr/bin/env")
    for ssh_agent_var in \
	LD_PRELOAD LD_LIBRARY_PATH LD_ORIGIN_PATH LD_DEBUG LD_DEBUG_OUTPUT \
	LD_PROFILE LD_USE_LOAD_BIAS LD_DYNAMIC_WEAK LD_SHOW_AUXV GCONV_PATH \
	GETCONF_DIR HOSTALIASES LOCALDOMAIN LOCPATH MALLOC_TRACE NLSPATH \
	RESOLV_HOST_CONF RES_OPTIONS TMPDIR TZDIR
    do
	if [ -n "${!ssh_agent_var+y}" ]; then
	    ssh_agent_args+=("${ssh_agent_var}=${!ssh_agent_var}")
	fi
    done
fi

# Now exec the real ssh-agent.
exec -a "$0" /usr/bin/ssh-agent.distrib "${ssh_agent_args[@]}" "$@"
