#!/bin/bash
set -eu
root=${1:?Pass an isolated scratch directory}
node_bin=$(dirname "$(command -v node)")
mkdir -p "$root/remote" "$root/keys"
sudo useradd -M -d "$root/remote" -s /bin/bash -G "$(id -gn)" profile-demo
sudo passwd -d profile-demo >/dev/null
ssh-keygen -q -t ed25519 -N '' -f "$root/keys/client"
ssh-keygen -q -t ed25519 -N '' -f "$root/keys/host"
cp "$root/keys/client.pub" "$root/remote/authorized_keys"
cat > "$root/remote/.profile" <<PROFILE
export PATH=${node_bin}:/usr/local/bin:/usr/bin:/bin
# The account uses Bash; its login initialization enables Zoxide for Bash.
eval "\$(zoxide init bash)"
PROFILE
printf '. "$HOME/.profile"\n' > "$root/remote/.bash_profile"
sudo chown -R profile-demo:profile-demo "$root/remote"
cat > "$root/sshd_config" <<EOF
ListenAddress 127.0.0.1
Port 22394
HostKey $root/keys/host
PidFile $root/sshd.pid
AuthorizedKeysFile $root/remote/authorized_keys
StrictModes no
PasswordAuthentication no
UsePAM no
AllowUsers profile-demo
Subsystem sftp internal-sftp
EOF
sudo mkdir -p /run/sshd
sudo /usr/sbin/sshd -f "$root/sshd_config" -E "$root/sshd.log"
sudo cat "$root/sshd.pid" > "$root/sshd-tracked.pid"
cat > "$root/client-config" <<EOF
Host profile-demo
  HostName 127.0.0.1
  Port 22394
  User profile-demo
  IdentityFile $root/keys/client
  UserKnownHostsFile $root/keys/known_hosts
  StrictHostKeyChecking accept-new
EOF
sudo cp "$root/client-config" /etc/ssh/ssh_config.d/99-profile-demo.conf
ssh profile-demo true
ssh profile-demo 'sh -c true'
set +e
ssh profile-demo 'sh -l -c true'
printf 'dash login exit: %s\n' "$?"
ssh profile-demo 'bash -l -c true'
printf 'bash login exit: %s\n' "$?"
