#!/bin/sh

set -e
set -x

export LC_ALL=C

uid="$(id -un)"
echo "Starting up as uid $uid, full id output: $(id)"
echo 'Process list:'
ps uwwx

unset SSH_AUTH_SOCK
unset SSH_AGENT_PID

echo 'No SSH agent variables in the environment, right?'
! printenv | egrep -e '^SSH_'

echo 'And ssh-add cannot see anything, either'
! ssh-add -l 2>&1

tempd="$(mktemp -d)"
echo "Using our tempdir $tempd"

echo 'OK, let us start an SSH agent...'
ssh-agent -s > "$tempd/ssh-agent.out"

echo 'Output:'
cat -- "$tempd/ssh-agent.out"

echo 'Loading it:'
. "$tempd/ssh-agent.out"
echo 'Environment:'
printenv | egrep -e '^SSH_'

echo 'Query it - no identities expected'
res=0
ssh-add -l > "$tempd/ssh-add.out" 2>"$tempd/ssh-add.err" || res="$?"
echo '- standard output:'
cat -- "$tempd/ssh-add.out"
echo '- standard error:'
cat -- "$tempd/ssh-add.err"
echo '- make sure it did not output the key'
! fgrep -e 'tanj@straylight' -- "$tempd/ssh-add.out"
echo '- make sure it failed'
[ "$res" != 0 ]

echo 'Now add a key'
install -m 600 -- debian/tests/data/id_tanj "$tempd/"
install -m 644 -- debian/tests/data/id_tanj.pub "$tempd/"
ssh-add -- "$tempd/id_tanj"
echo 'But did it work?'
res=0
ssh-add -l > "$tempd/ssh-add.out" 2>"$tempd/ssh-add.err" || res="$?"
echo '- standard output:'
cat -- "$tempd/ssh-add.out"
echo '- standard error:'
cat -- "$tempd/ssh-add.err"
echo '- make sure it succeeded'
[ "$res" = 0 ]
echo '- make sure it output some info about the key'
fgrep -e 'tanj@straylight' -- "$tempd/ssh-add.out"

echo 'Let us stop the agent'
ssh-agent -s -k > "$tempd/ssh-agent.out"
echo '- output:'
cat -- "$tempd/ssh-agent.out"
echo '- load it...'
. "$tempd/ssh-agent.out"
echo '- environment:'
! printenv | egrep -e '^SSH_'

kchome="$(mktemp -d)"
echo "Using keychain home directory $kchome and our tempdir $tempd"

keychain -q --dir "$kchome" --eval "$tempd/id_tanj" > "$tempd/1.out"

echo 'The output:'
cat -- "$tempd/1.out"

echo 'Loading it...'
eval "$(cat -- "$tempd/1.out")"

echo 'Let us take a look at the environment now...'
printenv | egrep -e '^SSH_'
if [ -z "$SSH_AUTH_SOCK" ]; then
	echo 'Uh, no SSH_AUTH_SOCK?' 1>&2
	exit 1
fi
ssh-add -l
ssh-add -l | fgrep -e 'tanj@straylight'

echo 'So what does keychain think is running?'
keychain -q --dir "$kchome" --query

echo 'And now --eval'
keychain -q --dir "$kchome" --eval

echo 'So let us try to add the OpenSSH key again...'
eval $(keychain -q --dir "$kchome" --eval debian/tests/data/id_tanj)

echo 'Environment...'
printenv | egrep -qe '^SSH_'

echo 'ssh-add...'
ssh-add -l

echo 'Query...'
keychain -q --dir "$kchome" --query

echo 'Eval...'
keychain -q --dir "$kchome" --eval

echo 'All done, it seems'
