#!/usr/bin/env bash

set -uo pipefail

usage() {
  echo "Usage: $0 <hosts_file> <public_key_file> [username]" >&2
  echo "Hosts must be listed one per line; blank lines and comments are ignored." >&2
}

if (($# < 2 || $# > 3)); then
  usage
  exit 2
fi

hosts_file="$1"
public_key_file="$2"
username="${3:-}"

command -v ssh-copy-id >/dev/null 2>&1 || {
  echo "Error: ssh-copy-id is not installed." >&2
  exit 1
}
[[ -r "$hosts_file" ]] || {
  echo "Error: hosts file is not readable: $hosts_file" >&2
  exit 1
}
[[ -r "$public_key_file" ]] || {
  echo "Error: public key is not readable: $public_key_file" >&2
  exit 1
}

host_count=0
failure_count=0
while IFS= read -r line || [[ -n "$line" ]]; do
  line="${line%%#*}"
  line="${line#"${line%%[![:space:]]*}"}"
  line="${line%"${line##*[![:space:]]}"}"
  [[ -z "$line" ]] && continue
  ((host_count += 1))
  if [[ "$line" == -* || "$line" == *[[:space:]]* ]]; then
    echo "Error: invalid host entry: $line" >&2
    ((failure_count += 1))
    continue
  fi
  target="$line"
  if [[ -n "$username" && "$target" != *@* ]]; then
    target="$username@$target"
  fi

  echo "Installing $public_key_file on $target"
  if ! ssh-copy-id -i "$public_key_file" "$target"; then
    echo "Error: key installation on $target failed." >&2
    ((failure_count += 1))
  fi
done <"$hosts_file"

if ((host_count == 0)); then
  echo "Error: no hosts were found in $hosts_file." >&2
  exit 1
fi
if ((failure_count > 0)); then
  echo "$failure_count of $host_count key installations failed." >&2
  exit 1
fi

echo "Installed the key on $host_count host(s)."
