#!/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:
}

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;
			cut -f1 -d: /etc/passwd|sed 's,.*,& r,'
			#for testing of multiple subdirectories
			if [ $dir = "/" ]; then
			    echo 'test1 d'
			    echo 'test2 d'
			fi
			if [ $dir = "test1" ]; then
			    echo "subtest1 d"
			fi
			if [ $dir = "test1/subtest1" ]; then
			    echo "subtest2 d"
			fi
			;;
		-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
			if [ $username = "test1" ]; then
			    echo "test1 d"
			fi
			if [ $username = "test2" ]; then
			    echo "test2 d"
			fi
			if [ $username = "test1/subtest1" ]; then
			    echo "subtest1 d"
			fi
			if [ $username = "test1/subtest1/subtest2" ]; then
			    echo "subtest2 d"
			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
			while read n;do
			    if echo $n|grep -qs "passwd:";then
				echo $n|sed 's,passwd:,,'|sed "s,.*,$username:&,"|/usr/sbin/chpasswd
			    else
				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
			;;
		--) shift; break
			;;
		*) Fatal "unrecognized option: $1"
			;;
	esac
	shift
done

