#!/bin/bash
PIS_SBIN="${PIS_SBIN:-/sbin}"
if [ -z "${PIS_LIBDIR:-}" ]; then
    case "$(uname -m)" in x86_64) PIS_LIBDIR=/usr/lib64/pis ;; *) PIS_LIBDIR=/usr/lib/pis ;; esac
fi
. "$PIS_LIBDIR/pis_lib" 2>/dev/null || . "$(dirname "$0")/pis_lib" || exit 1
pis_init || exit 1
username=$(dialog --stdout --backtitle "$PIS_BACKTITLE" --title "Add User" \
    --inputbox "Username:" 8 50) || exit 0
printf '%s' "$username" | grep -Eq '^[a-z_][a-z0-9_-]{0,31}$' || { pis_error "Use a valid lowercase Slackware username."; exit 1; }
password=$(dialog --stdout --insecure --backtitle "$PIS_BACKTITLE" --title "Add User" \
    --passwordbox "Password for '$username':" 8 50) || exit 0
repeat=$(dialog --stdout --insecure --backtitle "$PIS_BACKTITLE" --title "Add User" \
    --passwordbox "Repeat the password:" 8 50) || exit 0
[ -n "$password" ] || { pis_error "The password cannot be empty."; exit 1; }
[ "$password" = "$repeat" ] || { pis_error "The passwords do not match."; exit 1; }
wheel=NO
dialog --backtitle "$PIS_BACKTITLE" --title "Administrative User" \
    --yesno "Add '$username' to the wheel group?" 7 55 && wheel=YES
if pis_add_system_user "$username" "$password" "$wheel"; then
    unset password repeat
    pis_info "Add User" "User '$username' was created successfully. No password was stored by PIS."
else
    unset password repeat
    pis_error "User '$username' could not be created."
    exit 1
fi
