#!/bin/bash

## Copyright (C) 2019 - 2023 ENCRYPTED SUPPORT LP <adrelanos@whonix.org>
## Copyright (C) 2019 - 2019 Dipto
## See the file COPYING for copying conditions.

set -e

get_password() {
   ## author of contents of get_password function
   ## Dipto
   ## https://askubuntu.com/users/133486/dipto
   ##
   ## source of contents of get_password function
   ##
   ## https://askubuntu.com/a/299469/389275
   ##
   ## license:
   ## licensed under cc by-sa 3.0 with attribution required.

   unset password
   while IFS= read -p "$prompt" -r -s -n 1 char
   do
      # Enter - accept password
      if [[ $char == $'\0' ]] ; then
         break
      fi
      # Backspace
      if [[ $char == $'\177' ]] ; then
         prompt=$'\b \b'
         password="${password%?}"
      else
         prompt='*'
         password+="$char"
      fi
   done
}

if [ "$(id -u)" != "0" ]; then
   echo "ERROR: This must be run as root (sudo)!" >&2
   exit 1
fi

read -r -p "What user's password do you want to change? " user

if [ "$user" = "" ]; then
   echo "ERROR: No user supplied" >&2
   exit 1
fi

if ! id "$user" &>/dev/null ; then
   echo "ERROR: No such user '$user'" >&2
   exit 1
fi

echo -n "New password: "
echo
get_password
first_input="$password"
echo

echo -n "Retype new password: "
echo
get_password
second_input="$password"
echo

if [ ! "$first_input" = "$second_input" ]; then
   echo "ERROR: Sorry, passwords do not match.
password unchanged" >&2
   exit 1
fi

if [ "$first_input" = "" ]; then
   echo "ERROR: No password supplied" >&2
   exit 1
fi

echo "${user}:${password}" | chpasswd
