#!/bin/sh

PREREQ=""

prereqs() {
    echo "$PREREQ"
}

case "$1" in
    prereqs)
        prereqs
        exit 0
    ;;
esac

. /usr/share/initramfs-tools/hook-functions

dropbear_warn() {
    echo "dropbear: WARNING:" "$@" >&2
}

copy_exec /usr/sbin/dropbear /sbin
for so in $(ldconfig -p | sed -nr 's/^\s*libnss_files\.so\.[0-9]+\s.*=>\s*//p'); do
    copy_exec "$so"
done

if [ ! -f "$DESTDIR/etc/nsswitch.conf" ] || ! grep -q "^passwd:" "$DESTDIR/etc/nsswitch.conf"; then
    echo "passwd: files" >>"$DESTDIR/etc/nsswitch.conf"
fi
if [ ! -f "$DESTDIR/etc/nsswitch.conf" ] || ! grep -q "^group:" "$DESTDIR/etc/nsswitch.conf"; then
    echo "group: files" >>"$DESTDIR/etc/nsswitch.conf"
fi
if [ ! -f "$DESTDIR/etc/passwd" ] || ! grep -q "^root:" "$DESTDIR/etc/passwd"; then
    home="$(mktemp --directory -- "$DESTDIR/root-XXXXXXXXXX")" # avoid collisions with $rootmnt
    chmod 0700 -- "$home"
    echo "root:*:0:0::${home#"$DESTDIR"}:/bin/sh" >>"$DESTDIR/etc/passwd"
elif [ -f "$DESTDIR/etc/passwd" ] && home="$(grep -m1 "^root:" "$DESTDIR/etc/passwd" | cut -sd: -f6)" && \
        [ -n "$home" ] && [ -d "$DESTDIR/$home" ]; then
    home="$DESTDIR/$home"
else
    dropbear_warn "Couldn't find ~root, SSH login to initramfs won't work!"
    exit 1
fi
if [ ! -f "$DESTDIR/etc/group" ] || ! grep -q "^root:" "$DESTDIR/etc/group"; then
    echo "root:!:0:" >>"$DESTDIR/etc/group"
fi

# Copy config and host keys
mkdir -p -- "$DESTDIR/etc/dropbear"
if [ -e /etc/dropbear/initramfs/dropbear.conf ]; then
    cp -pt "$DESTDIR/etc/dropbear" "/etc/dropbear/initramfs/dropbear.conf"
fi

copied_hostkey="n"
for keytype in rsa ecdsa ed25519; do
    hostkey="/etc/dropbear/initramfs/dropbear_${keytype}_host_key"
    if [ -f "$hostkey" ]; then
        cp -pt "$DESTDIR/etc/dropbear" "$hostkey"
        copied_hostkey="y"
    fi
done
if [ "$copied_hostkey" = "n" ]; then
    dropbear_warn "Missing host keys, SSH login to initramfs won't work!"
fi

# Copy authorized_keys
mkdir -m0700 -- "$home/.ssh"
if [ -e /etc/dropbear/initramfs/authorized_keys ]; then
    cat /etc/dropbear/initramfs/authorized_keys
else
    for keytype in dsa rsa ecdsa ed25519; do
        pubkey="/etc/dropbear/initramfs/id_${keytype}.pub"
        if [ -e "$pubkey" ]; then
            cat "$pubkey"
        fi
    done
fi >"$home/.ssh/authorized_keys"

if ! grep -qE '^([^#]+)?(ssh-(rsa|ed25519)|ecdsa-sha2-nistp(256|384|521)) ' <"$home/.ssh/authorized_keys"; then
    dropbear_warn "Invalid authorized_keys file, SSH login to initramfs won't work!"
fi
