#!/bin/bash

# Nepracujeme s /etc/passwd, /etc/shadow a /etc/group, ale s kopiemi:

ROOT="."

passwd="${ROOT}/etc/passwd"
group="${ROOT}/etc/group"
shadow="${ROOT}/etc/shadow"
temp="/tmp/ptmp"
progname=$0			# Uschovame jmeno programu (pro chybove hlasky)

#====================== Inicializace promennych=========================

newhome=""			# --home  ...
newshell=""			# --shell ...
createhome=true			# --no-create-home
newuid=-1			# --uid ...
firstuid=-1			# --firstuid ...
lastuid=-1			# --lastuid ...
ingroup=""			# --ingroup ... 
newgid=-1			# --gid ...
nopassword=false		# --disabled-password
nologin=false			# --disabled-login
systemuser=false		# --system
groupuser=false			# --group
username=false			# ...
quiet=false			# --quiet
forcebadname=false		# --force-badname
				# --help
				# --version
configfile="${ROOT}/etc/adduser.conf"	# --conf FILE

if [ -f "$shadow" ]; then shadowenable=1; else shadowenable=0; fi

# ------------- Kontrola a zpracovani prikazove radky --------------
usage() {
    if [ $shadowenable -eq 1 ]; then
       echo "Usage: $progname [options] [--home DIR] [--shell SHELL] [--no-create-home] ">&2
       echo "                 [--uid ID] [--firstuid ID] [--lastuid ID] [--ingroup GROUP | --gid ID] ">&2
       echo "                 [--disabled-password] [--disabled-login] user">&2
       echo " ">&2
       echo "       $progname --system [options] [--home DIR] [--shell SHELL] [--no-create-home] ">&2
       echo "                 [--uid ID] [--group | --ingroup GROUP | --gid  ID]  ">&2
       echo "                 [--disabled-password]  [--disabled-login] user ">&2
       echo " ">&2
       echo "       $progname --group [options] [--gid ID] group">&2
       echo " ">&2
       echo "       $progname --group --system [options] [--gid ID] group">&2
       echo " ">&2
       echo "       $progname [options] user group">&2
       echo " ">&2
       echo "       COMMON OPTIONS">&2
       echo "       [--quiet] [--force-badname] [--help] [--version] [--conf FILE] ">&2
    else
       echo "Please set shadow!">&2
    fi
    exit 2
}

checkparam() {								#======= kontrola parametru, aby nemeli ":"
    if echo "$1" | grep ":" > /dev/null; then 
    	usage 
    fi
}

shouterror() {								#======= fce na error s kontrolou quiet
    if ! $quiet; then
        echo $1>&2 
    	exit 2 
    fi
}

shout() {								#======= fce na echo s kontrolou quiet
    if ! $quiet; then
        echo $1
    fi    
}

checkshadow() {								#======== kontrola shadow
    if [ $shadowenable -eq 0 ]; then
       echo $progname: $shadow not found>&2
       exit 14
    fi
}

myread () {								#======== fce na read ... kvuli "quiet", usage: myread mytitle myvar
    if ! $quiet; then 
		echo -n $1
		eval 'echo -n " [$'$2']: "'  #  Previous value.
		read local_var
		[ -n "$local_var" ] && eval $2=\$local_var
	fi	
}

if [ $# -eq 0 ]; then usage; fi						#========= kdyz nemam parametry kaslu na to

while [ $# -ne 0 ]; do							#========= jinak dokud je mam zpracovavam ;)
  checkparam $*;
  case $1 in
    --help)    			usage ;;
    --version) 			echo "$progname version 0.0.0 ;)" 
                 		exit 2 ;;
    --quiet)			quiet=true ;;
    --force-badname)		forcebadname=true ;;
    --conf)			shift; checkparam $*
    				if [ -f "$1" ]; then 
    				    configfile=$1 
    				else
    				    shouterror "$progname: $1: No such config file!"
    				fi ;;
    --group)			groupuser=true ;;
    --system)			systemuser=true ;;
    --home)			shift; checkparam $*
    				newhome=$1 ;;
    --shell)			shift; checkparam $*
    				if [ -f "$1" ]; then 
    				    newshell=$1 
    				else
    				    shouterror "$progname: $1: No such shell!"
    				fi ;;
    --no-create-home)		createhome=false ;;
    --uid)			shift; checkparam $*
    				newuid=$1 ;;
    --firstuid)			shift; checkparam $*
    				firstuid=$1 ;;
    --lastuid)			shift; checkparam $*
    				lastuid=$1 ;;
    --ingroup)			shift; checkparam $*
    				ingroup=$1 ;;
    --gid)			shift; checkparam $*
    				newgid=$1 ;;
    --disabled-password)	nopassword=true ;;
    --disabled-login)		nologin=true ;;
    *)				if [ $# -eq 2 ]; then 
    				    username=$1
    				    shift; groupname=$1
    				elif [ $# -eq 1 ]; then 
    				    username=$1
    				else
    				    usage 
    				fi ;;
  esac
  shift 
done

########################################
#     pridani uzivatele do skupiny     #
########################################

if [ "$username" ] && [ "$groupname" ]; then 
	if grep -n "^${groupname}:" $group > /dev/null && grep -n "^${username}:" $passwd > /dev/null; then 
		shout "Adding user \`$username\` to group \`$groupname\`."
	  	linepos=`grep -n "^${groupname}:" $group | cut -d: -f1`
	  	pwg=`grep -n "^${groupname}:" $group | cut -d: -f3`
	  	gid=`grep -n "^${groupname}:" $group | cut -d: -f4`
	  	rusers=`grep -n "^${groupname}:" $group | cut -d: -f5`
		newline=`echo "$groupname:$pwg:$gid:$rusers,$username" | sed 's/,,/,/g' | sed 's/:,/:/g'`
		if [ $linepos -gt 1 ]; then head -n $(($linepos-1)) "$group" > "$temp"; fi
		echo "$newline" >> "$temp";
		tail -n +$(($linepos+1)) "$group" >> "$temp"
		mv "$temp" "$group"
		exit 1	
	else
		shouterror "$progname: $username,$group: No such group or user!"
	fi
fi

########################################


# ----------------------- Zjisteni zda uz neexistuje -------------------------
if [ ! "$username" ] ; then
	shouterror "$progname: Please set user or group!"
elif $groupuser && grep -n "^${username}:" $group > /dev/null; then 
	shouterror "$progname: $username: Group such exists!"
elif grep -n "^${username}:" $passwd > /dev/null; then 
	shouterror "$progname: $username: User such exists!"	
fi

# ------------ Co jsme nezjistili z prikazu doplnime z configu ... ----------

#==============FIRST/LAST UID/GID=======================
if $systemuser || $groupuser; then
	if [ $firstuid -eq -1 ]; then
		firstuid=`grep "^FIRST_SYSTEM_UID=" $configfile | cut -d= -f2`
		let "firstuid-=1"
	fi
	if [ $lastuid -eq -1 ]; then
		lastuid=`grep "^LAST_SYSTEM_UID=" $configfile | cut -d= -f2`
		let "lastuid+=1"
	fi
else
	if [ $firstuid -eq -1 ]; then
		firstuid=`grep "^FIRST_UID=" $configfile | cut -d= -f2`
		let "firstuid-=1"
	fi
	if [ $lastuid -eq -1 ]; then
		lastuid=`grep "^LAST_UID=" $configfile | cut -d= -f2`
		let "lastuid+=1"
	fi
fi
#==============UID/GID=======================
if [ "$newuid" -eq -1 ] && $groupuser; then
	newuid=$firstuid
    for i in `grep "^[:alnum:]" $group | cut -d: -f3 | sort`; do
        if [ "$i" -lt "$lastuid" ] && [ "$i" -gt "$firstuid" ]; then 
           	newuid=$i
        fi
    done 
    let "newuid+=1"
	if [ "$newuid" -ge "$lastuid" ]; then
		echo "$progname: No more groups!">&2
		exit 2	
	fi
elif $groupuser; then
    for i in `grep "^[:alnum:]" $group | cut -d: -f3 | sort`; do
        if [ $i -eq $newuid ]; then 
			echo "$progname: $newuid: GID is used!">&2
			exit 2	
        fi
    done 	
elif [ $newuid -eq -1 ]; then
	newuid=$firstuid
    for i in `grep "^[:alnum:]" $passwd | cut -d: -f3 | sort`; do
        if [ "$i" -lt $lastuid ] && [ "$i" -gt $firstuid ]; then 
           	newuid=$i
        fi
    done 
    let "newuid+=1"
	if [ "$newuid" -ge $lastuid ]; then
		echo "$progname: No more users!">&2
		exit 2	
	fi
else
    for i in `grep "^[:alnum:]" $passwd | cut -d: -f3 | sort`; do
        if [ $i -eq $newuid ]; then 
			echo "$progname: $newuid: UID is used!">&2
			exit 2	
        fi
    done 	
fi

########################################
#          pridani skupiny             #
########################################

if $groupuser; then 
	shout "Adding new group \`$username\` ($newuid)."
	echo "$username:x:$newuid:" >> "$group" 
	exit 1
fi

########################################

#==============SHELL=======================
if [ "$newshell" == "" ]; then
	newshell=`grep "^DSHELL=" $configfile | cut -d= -f2`
fi

#==============INGROUP/GID=======================
if   [ "$ingroup" != "" ] && [ $newgid -eq -1 ]; then 
	newgid=`grep -n "^${ingroup}:" $group | cut -d: -f3`
	groupname=$ingroup
	if [ $newgid -gt -1 ]; then
		echo "$progname: $ingroup: No such group!">&2
		exit 2	
	fi	
elif [ $newgid -eq -1 ] && [ `grep "^USERGROUPS=" $configfile | cut -d= -f2` == "yes" ]; then
	newgid=$newuid
	groupname=$username
else
	newgid=`grep "^USERS_GID=" $configfile | cut -d= -f2`
	groupname="users"
fi

#==============HOME=======================
if [ "$newhome" == "" ]; then
	newhome=`grep "^DHOME=" $configfile | cut -d= -f2`
    if [ `grep "^GROUPHOMES=" $configfile | cut -d= -f2` == "yes" ]; then
    	newhome="${newhome}/${groupname}";
	fi
    if [ `grep "^LETTERHOMES=" $configfile | cut -d= -f2` == "yes" ]; then
        firstletter=`echo ${username} | cut -c1`
    	newhome="${newhome}/${firstletter}";
	fi
    newhome="${newhome}/${username}";
fi

if $nologin; then
	newpass="*"
elif [ $shadowenable -eq 1 ]; then
	newpass="x"
else
	newpass=""
fi	

shout "Adding user \`$username\` ..."
shout "Completing the user information for $username"

#=======ziskame zbytek informaci==========================================

correct="n"
while [ "$correct" == "n" ] || [ "$correct" == "N" ]; do
	myread " - Full Name" captionname
	myread " - Room Number" captionroom
	myread " - Work Phone" captionworktel
	myread " - Home Phone" captionhometel
	myread " - Other" captionother
	myread "Is the information correct? (y/n)" correct
done

newcomment="$captionname,$captionroom,$captionworktel,$captionhometel,$captionother"

#=======zapis do group====================================================

if [ `grep "^USERGROUPS=" $configfile | cut -d= -f2` == "yes" ]; then
	shout "Adding new group \`$username\` ($newuid)."
	echo "$username:x:$newuid:" >> "$group" 
fi

shout "Adding new user \`$username\` ($newuid) with group \`$groupname\`."

#=======zapis do passwd====================================================

echo "$username:$newpass:$newuid:$newgid:$newcomment:$newhome:$newshell" >> "$passwd" 

#=======vytvorime home, kdyz chce a neni to skupina========================

if $createhome && ! $groupuser; then
	dirmode=`grep "^DIR_MODE=" $configfile | cut -d= -f2`
	if [ "$dirmode" == "" ]; then 
		dirmode="0755"
	fi	
    shout "Creating home directory \`$newhome\`."
	mkdir -p -m $dirmode $newhome
fi

skel=`grep "^SKEL=" $configfile | cut -d= -f2`
if [ -d "$skel" ] && [ -s "$skel" ]; then
	shout "Copying files from \`$skel\`"
	cp "$skel"/* "$newhome"/.
fi

if [ $shadowenable -eq 1 ]; then
	secs=`date +%s`
	days=$(($secs / 86400))  
    echo "$username::$days:0:99999:7:::" >> "$shadow"
fi

if [ -d "$newhome" ]; then
	echo ">>> chown -R \"$newuid\":\"$newgid\" \"$newhome\""
fi

if ! $nopassword; then
	echo ">>> passwd $username"	
fi

exit 1