#!/bin/sh

ip_address="$1"

if echo "$ip_address" | grep -vqE '^([0-9]{1,3}\.){3}[0-9]{1,3}$'; then
  echo "ip_address $ip_address must match "'"^([0-9]{1,3}\.){3}[0-9]{1,3}$"'
  exit 1
fi

printf  '['
delimiter=""
ssh-keyscan "$ip_address" 2>/dev/null | while read -r line; do
  if echo "$line" | grep -qE "^$ip_address"' +(ssh|ecdsa)-[0-9A-Za-z+/_=@. -]+$'; then
    key_content="$(echo "$line" | awk '{ print $2 " " $3 }')"
    fingerprint_output="$(echo "$key_content" | ssh-keygen -l -E sha256 -f - | sed -E 's/^[0-9]+ SHA256:([0-9A-Za-z+/-]+) .+ \(([A-Z0-9]+)\)$/\1 \2/g')"
    sha256_hash="$(echo "$fingerprint_output" | awk '{ print $1 }')"
    key_type="$(echo "$fingerprint_output" | awk '{ print $2 }')"
    printf '%s\n  {"key_type":"%s", "content":"%s", "sha256":"%s"}' "$delimiter" "$key_type" "$key_content" "$sha256_hash"
    delimiter=","
  fi
done
printf '\n]\n'