#!/bin/sh

set -eu

# This script sets up sudoers if necessary, except that "puavo-os"-user
# and users in "puavo-os"-group always have "root"-access without a password.

# do nothing on hosts that have booted from network
if [ -e /run/puavo/nbd-server ]; then
  exit 0
fi

primary_user_conf_path=/etc/sudoers.d/primary_user
user_registration_conf_path=/etc/sudoers.d/user_registration

rm -f "$primary_user_conf_path" "$user_registration_conf_path"

superusers_mode=$(puavo-conf puavo.admin.superusers)

case "$superusers_mode" in
  limited-primary-user|primary-user-is-super)
    primary_user=$(puavo-conf puavo.admin.primary_user)
    if [ -z "$primary_user" -o \
         "$(puavo-conf puavo.admin.personally_administered)" != 'true' ]; then
      exit 0
    fi

    # make sure user actually exists in the system before providing
    # access rights
    if ! id -u "$primary_user" >/dev/null 2>&1; then
      echo "User '${primary_user}' does not exist!" >&2
      exit 1
    fi

    if [ "$superusers_mode" = 'primary-user-is-super' ]; then
      cat <<EOF > "${primary_user_conf_path}.tmp"
${primary_user} ALL=(ALL) ALL
${primary_user} ALL = NOPASSWD: /usr/sbin/puavo-pkg-update-from-gui
${primary_user} ALL = NOPASSWD: /usr/sbin/puavo-conf-local
EOF
    else
      cat <<EOF > "${primary_user_conf_path}.tmp"
${primary_user} ALL = /usr/sbin/puavo-reset-laptop-to-factory-defaults
${primary_user} ALL = NOPASSWD: /usr/sbin/puavo-pkg-update-from-gui
${primary_user} ALL = NOPASSWD: /usr/sbin/puavo-conf-local
EOF
    fi
    mv "${primary_user_conf_path}.tmp" "$primary_user_conf_path"
    ;;

  user-registration)
    cat <<EOF > "${user_registration_conf_path}.tmp"
guest ALL = NOPASSWD: /bin/cat /etc/puavo/ldap/password
guest ALL = NOPASSWD: /usr/lib/puavo-ltsp-client/firstlogin-to-account
guest ALL = NOPASSWD: /usr/sbin/puavo-conf-local
EOF
    mv "${user_registration_conf_path}.tmp" "$user_registration_conf_path"
    ;;

  '')
    ;;

  *)
    echo "Unsupported mode in puavo.admin.superusers: '${superusers_mode}'" >&2
    exit 1
    ;;
esac

exit 0
