#!/usr/bin/env bash
# mock-ssh — stands in for OpenSSH's client (PEPPA_SSH_BIN) in PEP-40 tests: a runner host is a
# directory, not a machine. Same syntax: `ssh [options] [user@]host command`; the command runs
# through `sh -c` "on the host" = in $MOCK_SSH_ROOT/<host> with its own HOME and TMUX_TMPDIR
# (its own tmux server; the socket dir is short — /tmp/mssh-<hash> — for the 104-byte socket path
# limit), stdin/stdout/exit code passed through like ssh does.
#   MOCK_SSH_DOWN=host1,host2  → "Connection refused", exit 255 (as ssh on a dead host)
#   <host>/home/.ssh/authorized_keys present → the -i key's .pub must be in it, else
#   "Permission denied (publickey)", exit 255 (BatchMode, no password prompt).
# Every call is appended to $MOCK_SSH_ROOT/calls.log.
set -uo pipefail
root="${MOCK_SSH_ROOT:?MOCK_SSH_ROOT is required}"
key="" port=22
while [[ $# -gt 0 ]]; do
  case "$1" in
    -i) key="$2"; shift 2 ;;
    -p) port="$2"; shift 2 ;;
    -o|-l|-F|-J|-E|-S) shift 2 ;;
    -T|-t|-tt|-q|-n|-v|-A|-N|-4|-6|-C) shift ;;
    --) shift; break ;;
    -*) echo "mock-ssh: unsupported option $1" >&2; exit 255 ;;
    *) break ;;
  esac
done
target="${1:?mock-ssh: no destination}"; shift
host="${target#*@}"
mkdir -p "$root"
printf '%s\t%s\t%s\n' "$target" "$port" "$*" >> "$root/calls.log"
if [[ ",${MOCK_SSH_DOWN:-}," == *",$host,"* ]]; then
  echo "ssh: connect to host $host port $port: Connection refused" >&2; exit 255
fi
h="$root/$host"
tmuxdir="/tmp/mssh-$(printf '%s' "$h" | cksum | cut -d' ' -f1)"
mkdir -p "$h/home" "$tmuxdir"
chmod 700 "$tmuxdir"
auth="$h/home/.ssh/authorized_keys"
if [[ -f "$auth" ]]; then
  if [[ -z "$key" || ! -f "$key.pub" ]] || ! grep -qF "$(cut -d' ' -f1,2 "$key.pub")" "$auth"; then
    echo "$target: Permission denied (publickey)." >&2; exit 255
  fi
fi
[[ $# -eq 0 ]] && { echo "mock-ssh: interactive sessions are not supported" >&2; exit 255; }
cd "$h/home" && HOME="$h/home" TMUX_TMPDIR="$tmuxdir" exec sh -c "$*"
