#!/bin/bash
#
# air-import-ssh-keys
#
# First-boot (and every-boot) oneshot: if /boot/firmware/ssh_authorized_keys
# exists, merge it into /home/air/.ssh/authorized_keys.
#
# Why:
#   The image randomises the 'air' account password at build time and
#   nobody — including Airdroper.org — knows it afterwards. That leaves
#   SSH public-key auth as the only supported entry.
#
#   Raspberry Pi Imager's customisation panel is one way to provision a key,
#   but operators who flash from the command line or want to rekey a deployed
#   SD card need a plain-file route: drop an authorized_keys file onto the
#   boot partition (FAT32, visible as a drive on Windows/macOS/Linux) and this
#   service picks it up on the next boot. The image README has advertised
#   this workflow for a while; this script is what makes it real.
#
# Behaviour:
#   - No-op if /boot/firmware/ssh_authorized_keys is absent (the common case).
#   - Idempotent: re-runs merge + dedupe instead of clobber. Re-editing the
#     boot-partition file and rebooting is how you rotate keys.
#   - Leaves the source file in place on purpose — operators expect to be
#     able to re-edit it later. Erasing it would also leak info about which
#     keys were imported vs. added manually.
#   - Logs to journald (visible with `journalctl -u air-import-ssh-keys`).

set -euo pipefail

SRC=/boot/firmware/ssh_authorized_keys
DEST_DIR=/home/air/.ssh
DEST=$DEST_DIR/authorized_keys

if [ ! -f "$SRC" ]; then
    exit 0
fi

# The ConditionPathExists= in the unit already guards the no-file case, but
# a file can still be empty or all-comments. Don't rewrite authorized_keys
# in that case — nothing to merge.
if ! grep -Eq '^[[:space:]]*(ssh-|ecdsa-|sk-)' "$SRC"; then
    echo "air-import-ssh-keys: $SRC has no public-key lines — skipping"
    exit 0
fi

install -d -m 0700 -o air -g air "$DEST_DIR"

# Merge: existing authorized_keys (if any) + source, stripping blank lines
# and comments, dedupe exact-line matches. This preserves keys the operator
# may have added by hand (e.g. via another running SSH session) while still
# picking up new ones from the boot partition.
#
# The boot partition is FAT32, so operators editing on Windows will produce
# \r\n line endings. Strip \r unconditionally — sshd rejects keys with
# trailing carriage returns, and a bare \r never appears in a valid pubkey.
tmp="$(mktemp "${TMPDIR:-/tmp}/air-import-ssh-keys.XXXXXX")"
trap 'rm -f "$tmp"' EXIT
{
    [ -f "$DEST" ] && cat "$DEST"
    cat "$SRC"
} | tr -d '\r' | awk 'NF && $0 !~ /^[[:space:]]*#/ && !seen[$0]++' > "$tmp"

# Only rewrite if the merged contents actually differ — avoids bumping
# mtime and journal noise on every boot when nothing changed.
if [ -f "$DEST" ] && cmp -s "$tmp" "$DEST"; then
    exit 0
fi

install -m 0600 -o air -g air "$tmp" "$DEST"
echo "air-import-ssh-keys: imported key(s) from $SRC → $DEST"
