#!/usr/bin/env bash
#
# ssh-authorize-machines.sh - let all of my machines SSH into this host.
#
# Usage:
#   ssh-authorize-machines.sh
#
# One-liner:
#   url=https://nithitsuki.com/scripts/ssh-authorize-machines.sh; if command -v curl >/dev/null; then curl -fsSL "$url" | bash; else wget -qO- "$url" | bash; fi
#
# What it does:
#   Creates ~/.ssh (mode 700) and ~/.ssh/authorized_keys (mode 600), then
#   appends each public key below only if its key body is not already present.
#   It never edits sshd config and never restarts a service.
#
# Guarantees: runs as your normal user and never uses sudo or root.
#
set -euo pipefail

KEYS=(
  "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIIsU+GWtpJckyMmBXMA0Frl+0xvufdN+paOIHmAgSRDO nithilan@osaka"
  "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIKtkgvbxwKjijotKCVXqzxNL4OcZXEwEn5HkU6hteDcj nithilan@kasukabe"
  "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIHAI8Lq0vS7i/c0GQDr5nNubV5dIlZ1Be7TB6eQ9cc6c nithilan@aster"
  "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIPwa4DBkYNFnNoApQTIzrckJkDX3vtdOvwG33DJxNzdr nithilan@lumen"
  "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAILFuZ4yJzMVHATm12Q7fF3fDEA2MVdWOHNXq9BxCRgTm nithilan@hino"
  "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIAkBL54GRUWykr9NbW/MIoIJwZLjJ6PbTvjwANeG4GbT nithilan@solis"
)

SSH_DIR="$HOME/.ssh"
AUTH_FILE="$SSH_DIR/authorized_keys"

die() {
  printf 'error: %s\n' "$*" >&2
  exit 1
}

# Prepare the directory and file with strict modes before writing anything.
prepare_ssh_files() {
  umask 077
  mkdir -p "$SSH_DIR"
  chmod 700 "$SSH_DIR"
  if [[ ! -e $AUTH_FILE ]]; then
    : >"$AUTH_FILE"
  fi
  chmod 600 "$AUTH_FILE"

  # A file without a trailing newline would glue the next key onto the last line.
  if [[ -s $AUTH_FILE ]] && [[ -n $(tail -c 1 "$AUTH_FILE") ]]; then
    printf '\n' >>"$AUTH_FILE"
  fi
}

# Print added/present for one key and append it only when missing.
authorize_key() {
  local entry=$1
  local body name
  body=$(printf '%s\n' "$entry" | awk '{print $2}')
  name=${entry##* }

  if grep -qF -- "$body" "$AUTH_FILE"; then
    printf 'present %s\n' "$name"
    return 1
  fi

  printf '%s\n' "$entry" >>"$AUTH_FILE"
  printf 'added %s\n' "$name"
  return 0
}

main() {
  local added=0 present=0 entry

  if [[ $EUID -eq 0 ]]; then
    die "do not run this as root; it only edits your own ~/.ssh and needs no sudo"
  fi

  prepare_ssh_files

  for entry in "${KEYS[@]}"; do
    if authorize_key "$entry"; then
      added=$((added + 1))
    else
      present=$((present + 1))
    fi
  done

  printf '\nDone: %d added, %d already present.\n' "$added" "$present"
  printf 'Public key login only works if sshd has PubkeyAuthentication on;\n'
  printf 'this script does not touch sshd config or restart services.\n'
}

main "$@"
