#!/bin/sh

set -e

CONFIG=/etc/glome/config
PRIVATE=$AUTOPKGTEST_TMP/private
PAM_LIB=$(ls /usr/lib/*/security/pam_glome.so)
PAM_CONFIG=/etc/pam.d/sshd
SSH_CONFIG=/etc/ssh/sshd_config.d/glome.conf

UMASK=$(umask)
umask 077
PUBLIC_KEY=$(glome genkey | tee $PRIVATE | glome pubkey)
umask "$UMASK"

sed -i "s/^#\\?public-key = .*/public-key = $PUBLIC_KEY/" $CONFIG
sed -i "1 { /glome/!i\\auth sufficient $PAM_LIB
          }" $PAM_CONFIG
cat <<EOF > $SSH_CONFIG
ChallengeResponseAuthentication yes
PermitRootLogin yes
EOF

service ssh restart

expect 2>$AUTOPKGTEST_ARTIFACTS/pam.log <<EOF
strace 1
spawn ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no root@localhost
set timeout 30
expect_before {
  eof { puts "\nExpect eof"; exit 1 }
  timeout { puts "\nExpect timeout"; exit 2 }
}
expect -re "GLOME: (v2/.*/)"
set resp [exec glome login --key $PRIVATE \$expect_out(1,string)]
expect "Password: "
send -- "\$resp\\n"
expect "# "
send "id\\n"
expect "uid=0(root)"
close
EOF
