#!/bin/bash
# This is a helper script for realmd
set -efu

_echo_help(){
  if [ "$LANG" = "ru_RU.UTF-8" ]; then
    echo "Этот скрипт выполняет донастройку системы после ввода в домен."
    echo "Использование: $0 профиль"
    echo "Профили: local — отключение доменной авторизации, sssd — если введено в домен через SSSD, winbind — через winbind."
  else
    echo "This script additionally configures the system after enrolling into a domain."
    echo "Usage: $0 profile"
    echo "Profiles: local — disable domain authorization, sssd — if enreolled into domain via SSSD, winbind — via winbind."
  fi
}

declare OPTIONS
OPTIONS="$(xargs -a '/var/lib/authselect/preserved-options' 2>/dev/null || echo '')"
CIFS_IDMAP_PLUGIN=''

case "${1:-}" in
  sssd | winbind )
    OPTIONS+=" with-mkhomedir with-libnss-role"

    case "$1" in
      sssd )
        CIFS_IDMAP_PLUGIN="cifs_idmap_sss.so"
      ;;
      winbind )
        OPTIONS+=" with-winbind-cache with-krb5 with-krb5-cache"
        CIFS_IDMAP_PLUGIN="idmapwb.so"
      ;;
    esac

    # libnss-role
    cat > /etc/role.d/domain.role << 'EOF'
Domain Users:users,cdrom,cdwriter,scanner,audio,video,floppy
Domain Admins:wheel
EOF
    if [ "$LANG" = "ru_RU.UTF-8" ]; then
      echo "Создан файл /etc/role.d/domain.role"
    else
      echo "Created file /etc/role.d/domain.role"
    fi
  ;;
  local )
    OPTIONS+=" $(xargs -a '/var/lib/authselect/preserved-options-nodomain' 2>/dev/null || echo '')"
  ;;
  help )
    _echo_help
    exit 0
  ;;
  * )
    _echo_help
    exit 1
  ;;
esac

set -x
# $1: "winbind" or "sssd" or "local"
# shellcheck disable=SC2086
authselect select "$1" $OPTIONS --force

if [ -n "$CIFS_IDMAP_PLUGIN"  ]; then
    alternatives --set cifs-idmap-plugin "/usr/lib64/cifs-utils/${CIFS_IDMAP_PLUGIN}"
fi
