#!/bin/sh
# Creates the kiosk account. Identical logic to hosts/kitchen-display's/
# hosts/touch-panel's own 0100-user-setup.hook.chroot.
set -eu

. /etc/door-panel-agent/config.env

if ! id "$KIOSK_USERNAME" >/dev/null 2>&1; then
  useradd --create-home --shell /bin/bash --comment "Door panel kiosk session" "$KIOSK_USERNAME"
fi

for grp in audio video input render dialout netdev plugdev seat _seatd; do
  if getent group "$grp" >/dev/null 2>&1; then
    adduser "$KIOSK_USERNAME" "$grp" >/dev/null
  fi
done

passwd --lock "$KIOSK_USERNAME" >/dev/null
adduser "$KIOSK_USERNAME" sudo >/dev/null

cat > "/etc/sudoers.d/010-${KIOSK_USERNAME}" <<EOF
${KIOSK_USERNAME} ALL=(ALL) NOPASSWD: ALL
EOF
chmod 0440 "/etc/sudoers.d/010-${KIOSK_USERNAME}"

mkdir -p /etc/ssh/sshd_config.d
cat > /etc/ssh/sshd_config.d/10-door-panel.conf <<'EOF'
PermitRootLogin no
PasswordAuthentication no
KbdInteractiveAuthentication no
PubkeyAuthentication yes
EOF

if [ -d "/home/${KIOSK_USERNAME}/.ssh" ]; then
  chmod 700 "/home/${KIOSK_USERNAME}/.ssh"
  [ -f "/home/${KIOSK_USERNAME}/.ssh/authorized_keys" ] && \
    chmod 600 "/home/${KIOSK_USERNAME}/.ssh/authorized_keys"
fi

chown -R "${KIOSK_USERNAME}:${KIOSK_USERNAME}" "/home/${KIOSK_USERNAME}"

systemctl enable ssh >/dev/null 2>&1 || true
