script-user-add 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. #!/usr/bin/env bash
  2. # Add a user to the Hartman Lab server
  3. # Copyright 2021-2025 Bryan C. Roessler
  4. # Licensed under the Apache License, Version 2.0
  5. p="${BASH_SOURCE[0]%/*}"; [[ -r $p/script-functions ]] && . "$p"/script-functions || exit 1
  6. echo "Usage: sudo $0 [username] [password]"
  7. is_root
  8. case $# in
  9. 0) user=$(prompt user); password=$(prompt password) ;;
  10. 1) user="$1"; password=$(prompt password) ;;
  11. 2) user="$1"; password="$2" ;;
  12. *) echo "Too many arguments provided"; exit 1 ;;
  13. esac
  14. useradd_cmd=(useradd -m -U)
  15. if id -u "$user" &>/dev/null; then
  16. ask_ok "User $user exists. Run script-user-remove first?" || exit $?
  17. "$p/script-user-remove" "$user" || exit $?
  18. fi
  19. ask_ok "Create user $user with password $password?" || exit $?
  20. restore=0
  21. if [[ -d /mnt/array/home-retired/$user ]]; then
  22. ask_ok "Restore user $user's files from /mnt/array/home-retired/$user?" && restore=1
  23. fi
  24. groups=()
  25. samba=0
  26. if ask_ok "Enable shared file access for user $user?"; then
  27. groups+=("smbgrp")
  28. samba=1
  29. fi
  30. ask_ok "Make $user an admin?" && groups+=("wheel")
  31. if (( ${#groups[@]} )); then
  32. useradd_cmd+=("-G" "$(IFS=,; echo "${groups[*]}")")
  33. fi
  34. useradd_cmd+=("$user")
  35. "${useradd_cmd[@]}"
  36. echo "$user:$password" | chpasswd
  37. if ((restore)); then
  38. if rsync -av --progress=info2 "/mnt/array/home-retired/$user/" "/home/$user/"; then
  39. ask_ok "User $user's files successfully restored, remove backup at /mnt/array/home-retired/$user?" && \
  40. rm -rf "/mnt/array/home-retired/$user"
  41. fi
  42. fi
  43. if ((samba)); then
  44. (echo "$password"; echo "$password") | smbpasswd -a -s "$user"
  45. fi
  46. ask_ok "Prompt user to reset password on next login?" &&
  47. passwd --expire "$user" &&
  48. echo "NOTE: The file sharing (smbpasswd) will not be changed"
  49. # Copy manual to user desktop
  50. desktop="/home/$user/Desktop"
  51. mkdir -p "$desktop"
  52. "$p/script-deploy-manual" "$user"
  53. exit 0