#!/bin/sh
# realadm-updater-setup: what the realadm-updater package needs outside its own files
# (realed2/realadm#6).  postinst runs it, and so does realadm's setup-remote once it has
# made the remote user.  Running it again changes nothing.
#
# - The sudoers file must be 0440 and pass visudo; one that does not is moved aside, so
#   sudo keeps working.
# - When the package carries a key for remote (remote.pub), remote's authorized_keys gets
#   that one key, able to run only the updater, and only from this host (connections
#   through a1's channel socket arrive on localhost).  sshd reads the file as remote, so it
#   and its directory are root's with group remote: remote can read them, not change
#   them, and no one else can read them.  remote's home is made the same way when it is
#   missing; one that exists is left as it is (on adm, setup-remote keeps it remote's).
# - remote's shell becomes realadm-updater-shell, which runs only the updater, since sshd
#   runs even a forced command through the user's shell.  remote joins the ssh group when
#   sshd's AllowGroups names it.
set -e
share=/usr/share/realadm-updater
sudoers=/etc/sudoers.d/realadm-updater
shell=/usr/sbin/realadm-updater-shell

if [ -e $sudoers ]; then
    chown root:root $sudoers
    chmod 0440 $sudoers
    if ! visudo -cq; then
        mv $sudoers $sudoers.disabled
        echo "realadm-updater-setup: sudoers check failed; moved $sudoers to $sudoers.disabled" >&2
    fi
fi

key=$(grep -E '^ssh-[a-z0-9]+ ' $share/remote.pub 2>/dev/null | head -n 1 || :)
pw=$(getent passwd remote || :)
if [ -n "$key" ] && [ -n "$pw" ]; then
    home=$(echo "$pw" | cut -d: -f6)
    [ "$(echo "$pw" | cut -d: -f7)" = $shell ] || usermod -s $shell remote
    [ -d "$home" ] || install -d -o root -g remote -m 0750 "$home"
    install -d -o root -g remote -m 0750 "$home/.ssh"
    tmp=$(mktemp "$home/.ssh/.authorized_keys.XXXXXX")
    printf 'restrict,from="127.0.0.1,::1",command="/usr/bin/sudo -n /usr/sbin/realadm-updater" %s\n' "$key" > "$tmp"
    chown root:remote "$tmp"
    chmod 0640 "$tmp"
    mv "$tmp" "$home/.ssh/authorized_keys"
    if getent group ssh > /dev/null && sshd -T 2> /dev/null | grep -qiE '^allowgroups( .*)? ssh( |$)'; then
        id -nG remote | tr ' ' '\n' | grep -qx ssh || usermod -a -G ssh remote
    fi
fi
exit 0
