#!/usr/bin/env bash
TEST_CATEGORY=core

level=$1
if [ -z "$level" ]; then
  level=1
else
  shift
fi
echo "starting: ${BASH_SOURCE[@]##*/} <LOG_LEVEL=$level>"

source this
source test.suite

log.level $level

# Verify the WODA Host blocks in $HOME/.ssh/config use the portable literal
# `~/.ssh/id_ed25519` form — NOT the hardcoded `/home/<user>/.ssh/id_ed25519`
# form that user.init was producing via $sshDir shell expansion.
#
# Why portable matters: when the same shared config is propagated across
# multiple users (root, developking, bash-user, oosh-user, test, ...),
# `~` lets ssh expand it per-user at read time. A literal /home/bash-user/...
# only works for one user.

cfg="$HOME/.ssh/config"

test.case $level "ssh.config.woda.portable: $USER has ~/.ssh/config" test -f "$cfg"
if [ ! -f "$cfg" ]; then
  expect.fail "$cfg missing"
  test.suite.save.results
  return 0 2>/dev/null || exit 0
else
  expect.pass "$cfg present"
fi

# For each WODA Host, the IdentityFile line must use the portable ~/.ssh form.
# We extract the block from `Host WODA.X` to the next `Host ` line and grep.
woda_hosts=(WODA.test WODA.dev.root WODA.dev)

for host in "${woda_hosts[@]}"; do
  block=$(awk -v h="^Host $host\$" '
    $0 ~ h {found=1; print; next}
    found && /^Host / {found=0}
    found {print}
  ' "$cfg")

  test.case $level "ssh.config.woda.portable: $host uses ~/.ssh/id_ed25519" true
  if echo "$block" | grep -Fq "IdentityFile ~/.ssh/id_ed25519"; then
    expect.pass "$host IdentityFile is portable"
  else
    actual=$(echo "$block" | grep -E "^[[:space:]]*IdentityFile" | head -1 | sed 's/^[[:space:]]*//')
    expect.fail "$host IdentityFile not portable — got: '${actual:-<missing>}'"
  fi
done

test.case $level "ssh.config.woda.portable: no hardcoded /home/ in WODA IdentityFile lines" true
hardcoded=$(awk '
  /^Host WODA\./ {inblock=1; next}
  inblock && /^Host / {inblock=0}
  inblock && /^[[:space:]]*IdentityFile[[:space:]]+\/home\// {print NR": "$0}
' "$cfg")
if [ -z "$hardcoded" ]; then
  expect.pass "no hardcoded /home/ paths in WODA IdentityFile lines"
else
  expect.fail "found hardcoded paths: $hardcoded"
fi

test.suite.save.results
