#!/bin/bash


##
## code
##

chmod 440 /etc/sudoers.d/* -R

KEYS=/etc/rsync/keys
RSYNC_HOME=/var/lib/rsync

mkdir -p "$RSYNC_HOME/.ssh"

if ! egrep '^[^:]+:x:101:101:' /etc/passwd; then
    ## Then it is a first run of this container, users
    ## need to be created. Notice that container will be
    ## re-created anew if user config was changed.
    for user_dir in /etc/rsync/keys/admin/* /etc/rsync/keys/recover; do
        [ -d "$user_dir" ] || continue
        user="${user_dir##*/}"
        [ "$user" != "rsync" ] || continue

        adduser -S "$user" -h "$user_dir" -G rsync &&
            chown "$user":rsync "$user_dir" || {
                echo "Error: couldn't create user $user or chown '$user_dir'." >&2
                exit 1
            }
        ## Without this, account is considered locked by SSH
        sed -ri "s/^$user:\!:/$user:*NP*:/g" /etc/shadow

        ## Withouth this, force-command will not run
        sed -ri "s%^($user.*:)[^:]+$%\1/bin/bash%g" /etc/passwd

    done
fi

log="/var/log/rsync/ssh-admin-cmd-validate.log"
touch "$log"
chown rsync:rsync "$log"
chmod g+rw "$log"


ssh-update-keys

## Give back PID 1 so that ssh can receive signals
exec /usr/sbin/sshd -D -e