script-user-remove 1022 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. #!/usr/bin/env bash
  2. # Remove a user from the server
  3. # Copyright 2021-2023 Bryan C. Roessler
  4. parent="${BASH_SOURCE[0]}"
  5. parent=${parent%/*}
  6. [[ -f $parent/script-functions ]] && . "$parent"/script-functions || exit 1
  7. is_root
  8. echo "This script supports one optional argument, a username"
  9. if [[ $# -eq 1 ]]; then
  10. user="$1"
  11. else
  12. prompt user
  13. fi
  14. if ! id -u "$user" &>/dev/null; then
  15. echo "User $user does not exist"
  16. exit 1
  17. fi
  18. ask_ok "Remove user $user?" || exit 1
  19. killall -u "$user"
  20. if ask_ok "Backup /home/$user?" && [[ -d /home/$user ]]; then
  21. if [[ ! -d /mnt/array/home-retired/$user ]]; then
  22. btrfs subvolume create /mnt/array/home-retired/"$user" || exit 1
  23. fi
  24. rsync -av /home/"$user"/ /mnt/array/home-retired/"$user" || exit 1
  25. fi
  26. smbpasswd -x "$user"
  27. sed -i "/$user/d" /etc/subuid
  28. sed -i "/$user/d" /etc/subgid
  29. if ! userdel -fr "$user"; then
  30. ask_ok "Userdel failed, kill processes again and retry?" || exit 1
  31. killall -u "$user" -s SIGKILL
  32. userdel -fr "$user"
  33. fi
  34. exit $?