#!/bin/sh

#----------------------------------------------------------------------
# Create a temp script to echo the SSH password, used by SSH_ASKPASS
#----------------------------------------------------------------------

# Exit on errors
set -e

SSH_ASKPASS_SCRIPT=$(mktemp -t ssh-askpass-script) || { echo "Failed to create temp file"; exit 1; }
cat > ${SSH_ASKPASS_SCRIPT} <<EOL
#!/bin/bash
echo "\${ST_SSH_PASSPHRASE}"
EOL
chmod u+x ${SSH_ASKPASS_SCRIPT}

# Set no display, necessary for ssh to play nice with setsid and SSH_ASKPASS.
export DISPLAY=:0
 
# Tell SSH to read in the output of the provided script as the password.
# We still have to use setsid to eliminate access to a terminal and thus avoid
# it ignoring this and asking for a password.
export SSH_ASKPASS=${SSH_ASKPASS_SCRIPT}

added_keys="ssh-add -l"
eval $added_keys

if [ ! $(echo $added_keys | grep -o -e $1) ]; then
	# Passphrase sent to ssh-add explicitly rather than exported so it's not exposed
	# to anything else we might call from this script later (more secure)
    ST_SSH_PASSPHRASE="${2}" ssh-add -K $1
fi

rm -f ${SSH_ASKPASS_SCRIPT}