#!/usr/bin/env bash
# Add a user to the Hartman Lab server
# Copyright 2021-2025 Bryan C. Roessler
# Licensed under the Apache License, Version 2.0
p="${BASH_SOURCE[0]%/*}"; [[ -r $p/script-functions ]] && . "$p"/script-functions || exit 1

echo "Usage: sudo $0 <username>"

is_root

case $# in
  0) user=$(prompt user) ;;
  1) user="$1" ;;
  *) echo "Too many arguments provided"; exit 1 ;;
esac

useradd_cmd=(useradd -m -U)

if id -u "$user" &>/dev/null; then
  ask_ok "User $user exists. Run script-user-remove first?" || exit $?
  script-user-remove "$user" || exit $?
fi

# Generate random temporary password to provide to user
password=$(tr -dc 'A-HJ-NP-Za-km-z2-9' </dev/urandom | head -c12)

ask_ok "Create user $user with password $password?" || exit $?

restore=0
if [[ -d /mnt/array/home-retired/$user ]]; then
  ask_ok "Restore user $user's files from /mnt/array/home-retired/$user?" && restore=1
fi

groups=()
samba=0
if ask_ok "Enable shared file access for user $user?"; then
  groups+=("smbgrp")
  samba=1
fi

ask_ok "Make $user an admin?" && groups+=("wheel")

if (( ${#groups[@]} )); then
  useradd_cmd+=("-G" "$(IFS=,; echo "${groups[*]}")")
fi
useradd_cmd+=("$user")

"${useradd_cmd[@]}"
echo "$user:$password" | chpasswd

if ((restore)); then
  if rsync -av --progress=info2 "/mnt/array/home-retired/$user/" "/home/$user/"; then
    ask_ok "User $user's files successfully restored, remove backup at /mnt/array/home-retired/$user?" && \
      rm -rf "/mnt/array/home-retired/$user"
  fi
fi

if ((samba)); then
  (echo "$password"; echo "$password") | smbpasswd -a -s "$user"
fi

ask_ok "Prompt user to reset password on next login?" &&
  passwd --expire "$user" &&
  echo "NOTE: The file sharing (smbpasswd) will not be changed"

echo "User successfully created, provide them with the following for first login"
echo "Username: $user"
echo "Password: $password"

exit 0