#!/usr/bin/env bash

set -uo pipefail

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

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

source_file="$1"
hosts_file="$2"
remote_directory="$3"
username="${4:-}"

command -v scp >/dev/null 2>&1 || {
  echo "Error: scp is not installed." >&2
  exit 1
}
[[ -f "$source_file" ]] || {
  echo "Error: source file not found: $source_file" >&2
  exit 1
}
[[ -r "$hosts_file" ]] || {
  echo "Error: hosts file is not readable: $hosts_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 "Copying $source_file to $target:$remote_directory"
  if ! scp -- "$source_file" "$target:$remote_directory"; then
    echo "Error: copy to $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 copies failed." >&2
  exit 1
fi

echo "Copied $source_file to $host_count host(s)."
