#!/bin/bash
#
# setup-ssh.sh - Configure SSH for the toes CLI user
#
# This script:
#   1. Creates a `cli` system user with /usr/local/bin/toes as shell
#   2. Suppresses login banner via .hushlogin
#   3. Sets an empty password on `cli` for passwordless SSH
#   4. Adds a Match block in sshd_config to allow empty passwords for `cli`
#   5. Adds /usr/local/bin/toes to /etc/shells
#   6. Restarts sshd
#
# Run as root on the toes machine.
# Usage: ssh cli@toes.local

set -euo pipefail

TOES_SHELL="/usr/local/bin/toes"
SSHD_CONFIG="/etc/ssh/sshd_config"

echo "==> Setting up SSH CLI user for toes"

# 1. Create cli system user
if ! id cli &>/dev/null; then
  useradd --system --home-dir /home/cli --shell "$TOES_SHELL" --create-home cli
  echo "  Created cli user"
else
  echo "  cli user already exists"
fi

# 2. Suppress login banner (MOTD, last login, etc.)
touch /home/cli/.hushlogin
chown cli:cli /home/cli/.hushlogin 2>/dev/null || true
echo "  Created .hushlogin"

# 3. Set empty password
passwd -d cli
echo "  Set empty password on cli"

# 4. Add Match block for cli user in sshd_config
if ! grep -q 'Match User cli' "$SSHD_CONFIG"; then
  cat >> "$SSHD_CONFIG" <<EOF

# toes CLI: allow passwordless SSH for the cli user
Match User cli
    PermitEmptyPasswords yes
EOF
  echo "  Added Match User cli block to sshd_config"
else
  echo "  sshd_config already has Match User cli block"
fi

# 5. Ensure /usr/local/bin/toes is in /etc/shells
if ! grep -q "^${TOES_SHELL}$" /etc/shells; then
  echo "$TOES_SHELL" >> /etc/shells
  echo "  Added $TOES_SHELL to /etc/shells"
else
  echo "  $TOES_SHELL already in /etc/shells"
fi

# Warn if toes binary doesn't exist yet
if [ ! -f "$TOES_SHELL" ]; then
  echo "  WARNING: $TOES_SHELL does not exist yet"
  echo "  Create it with: ln -sf /path/to/toes/cli $TOES_SHELL"
fi

# 6. Restart sshd
echo "  Restarting sshd..."
systemctl restart sshd || service ssh restart || true

echo "==> Done. Connect with: ssh cli@toes.local"
