#!/usr/bin/env bash
# Install Preston Ursini's public key for the current account.
# Usage: curl -fsSL https://prestonursini.com/ssh | bash
# Public key: https://prestonursini.com/downloads/public_keys/preston_ssh.txt
(
    set -eu
    umask 077
    : "${HOME:?HOME must point to the account receiving the key}"
    key='ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIIit8iMku3xd6QXTZ3h8BbYbtKBu+QNS1SA3W1Y0cTWb preston'
    key_data='AAAAC3NzaC1lZDI1NTE5AAAAIIit8iMku3xd6QXTZ3h8BbYbtKBu+QNS1SA3W1Y0cTWb'
    ssh_dir="$HOME/.ssh"
    authorized_keys="$ssh_dir/authorized_keys"
    mkdir -p -- "$ssh_dir"
    chmod 700 -- "$ssh_dir"
    touch -- "$authorized_keys"
    chmod 600 -- "$authorized_keys"

    # Match key material even if an existing entry uses a different comment
    # or has access restrictions. Preserve those restrictions.
    if awk -v key="$key_data" '
        /^[[:space:]]*#/ { next }
        { for (i = 1; i < NF; i++) if ($i == "ssh-ed25519" && $(i + 1) == key) found = 1 }
        END { exit !found }
    ' "$authorized_keys"; then
        printf '%s\n' "Preston's SSH key is already installed in $authorized_keys"
    else
        # Separate the new key from an existing final line without a newline.
        if [ -s "$authorized_keys" ] && [ -n "$(tail -c 1 -- "$authorized_keys")" ]; then
            printf '\n' >> "$authorized_keys"
        fi
        printf '%s\n' "$key" >> "$authorized_keys"
        printf '%s\n' "Installed Preston's SSH key in $authorized_keys"
    fi
)
