#!/usr/bin/env bash
# Reset a user password on the 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

if ! id -u "$user" &>/dev/null; then
  echo "User $user does not exist"
  exit 1
fi

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

if ask_ok "Reset $user's password"; then
  echo "$user:$password" | chpasswd
  (echo "$password"; echo "$password") | smbpasswd -a -s "$user"
fi

ask_ok "Prompt user to reset password on next login?" &&
  passwd --expire "$user"

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

exit 0
