#!/bin/sh
# 20231217
# Jan Mojzis
# Public domain.


# change directory to $AUTOPKGTEST_TMP
cd "${AUTOPKGTEST_TMP}"

# we need tools from /usr/sbin
PATH="/usr/sbin:${PATH}"
export PATH

# backup ~/.ssh
rm -rf ~/.ssh.tinysshtest.bk
[ -d ~/.ssh ] && mv ~/.ssh ~/.ssh.tinysshtest.bk
mkdir -p ~/.ssh
chmod 700 ~/.ssh

# run tinysshd on port 10000
rm -rf sshkeydir
tinysshd-makekey -q sshkeydir
tcpserver -HRDl0 127.0.0.1 10000 tinysshd -v -- sshkeydir 2>tinysshd.log &
tcpserverpid=$!
# Give some extra time for tcpserver to start,
# to avoid flaky test failures on slower testbeds
sleep 1

cleanup() {
  ex=$?
  echo
  echo "tinysshd.log:"
  cat tinysshd.log
  rm -rf ~/.ssh sshkeydir tinysshd.log ssh.log testfile1 testfile2
  [ -d ~/.ssh.tinysshtest.bk ] && mv ~/.ssh.tinysshtest.bk ~/.ssh
  #kill tcpserver
  kill -TERM "${tcpserverpid}" 1>/dev/null 2>/dev/null || :
  kill -KILL "${tcpserverpid}" 1>/dev/null 2>/dev/null || :
  exit "${ex}"
}
trap "cleanup" EXIT TERM INT

# create authorization keys
ssh-keygen -t ed25519 -q -N '' -f ~/.ssh/id_ed25519 || exit 10
cp -pr ~/.ssh/id_ed25519.pub ~/.ssh/authorized_keys || exit 11

# add server key to the known_hosts
ssh-keyscan -t ed25519 -H -p 10000 127.0.0.1 2>/dev/null > ~/.ssh/known_hosts

# testfiles
testfile1="`pwd`/testfile1"
testfile2="`pwd`/testfile2"

# create random file
dd if=/dev/urandom "of=${testfile1}" bs=1M count=1 2>/dev/null
echo -n 'ahoj' > ${testfile1}

# run in terminal (-tt) mode with stdin redirected to /dev/null (-n)
ssh -n -tt -p 10000 127.0.0.1 "cat ${testfile1}" 2>/dev/null | sed 's/abcdefghijklmnopqrstuvwxyz//' > testfile2

if [ x"`sha256sum < ${testfile1}`" = x"`sha256sum < ${testfile2}`" ]; then
  echo 'ssh exec in terminal with stdin redirected to /dev/null: ok'
else
  echo 'ssh exec in terminal with stdin redirected to /dev/null: failed'
  echo testfile1:
  echo ">>`cat ${testfile1}`<<"
  echo testfile2:
  echo ">>`cat ${testfile2}`<<"
  exit 2
fi
