#!/bin/sh

PROG="${0##*/}" #program name

print_version()
{
	cat <<EOF
$PROG version @VERSION@

Written by Stanislav Ievlev

Copyright (C) 2003-2004 ALT Linux Team
EOF
	exit
}

print_usage()
{
	[ "$1" = 0 ] || exec >&2
	cat <<EOF
Usage: $PROG [options] 

utility to manipulate system users: add, delete, modify

Valid options are:
  -h, --help	display help screen
  -v, --version	display version information
  -l, --list	get list of available users
  -f, --find	check for user existance
  -d, --delete	delete some user
  -r, --read	read user information
  -w, --write	write user information

Report bugs to <inger@altlinux.org>
EOF
	[ -n "$1" ] && exit "$1" || exit
}

field()
{
    echo $1|cut -f$2 -d:
}


get_minuid()
{
	grep -m1 UID_MIN /etc/login.defs|
	    sed 's,UID_MIN[[:space:]]*,,'|
	    sed 's,[[:space:]]*$,,'
}

TEMP=`getopt -n $PROG -o h,v,l:,d:,r:,w:,f: -l help,version,list:,delete:,read:,write:,find: -- "$@"` || print_usage
eval set -- "$TEMP"

while :; do
	case "$1" in
		-h|--help) print_usage 0
			;;
		-v|--version) print_version
			;;
		-l|--list)
			shift;dir=$1;
			min_uid=$(get_minuid)
			cat /etc/passwd|
			awk -F : "{if (\$3 >= "$min_uid") print \$1,\"r\" }"
			;;
		-d|--delete)
			shift;username=$1;
			/usr/sbin/userdel $1
			;;
		-f|--find)
			shift;username=$1;
			if egrep -qs "^$username:" /etc/passwd; then
			    echo "$username r"
			fi
			;;
		-r|--read)
			shift;username=$1;
			line=$(grep "^$username:" /etc/passwd)
			[ -z "$line" ] && exit 0 
			echo "uid:$(field "$line" "3")"
			echo "gid:$(field "$line" "4")"
			echo "gecos:$(field "$line" "5")"
			echo "home:$(field "$line" "6")"
			echo "shell:$(field "$line" "7")"
			;;
		-w|--write)
			shift;username=$1;
			if grep -qs "^$username:" /etc/passwd;then
			    cmd="/usr/sbin/usermod"
			else
			    cmd="/usr/sbin/useradd"
			fi
			need_chpasswd=
			while read n;do
			    if echo $n|grep -qs '^passwd:';then
				need_chpasswd=$n
			    elif echo $n|egrep -qs 'gid|gecos|home|shell'; then
				params="$params $(echo $n|sed 's,uid:\(.*\),-u \1,
				s,gid:\(.*\),-g \1,
				s,gecos:\(.*\),-c \"\1\",
				s,home:\(.*\),-d \1,
				s,shell:\(.*\),-s \1,
				')"
			    fi
			done
			eval $cmd $params $username
			if [ -n "$need_chpasswd" ];then
			    printf '%s\n' "$need_chpasswd" |sed 's,^passwd:,,'|sed "s,.*,$username:&,"|/usr/sbin/chpasswd
			fi
			;;
		--) shift; break
			;;
		*) Fatal "unrecognized option: $1"
			;;
	esac
	shift
done

