#!/bin/sh
USERLISTFD=/tmp/.storageusr.list
FILE_Group="/etc/group"
FILE_Passwd="/etc/passwd"
index=$2
user=$3
passwd=$4
path_access=$5

gen_user_ID()
{
    local userID=501
    while [ "$userID" -le "520" ]
    do
        local exist=`grep -c "$userID" $FILE_Passwd`
        if [ "$exist" == "0" ]; then
            break
        fi
        userID=`expr $userID + 1`
    done
    echo -n $userID
}

add_storage_user()
{
	local uid=`gen_user_ID`
	if [ -n "$user" ]; then
	    if [ "$user" != "admin" ];then
	        if [ -n "$path_access" ];then
		    echo "$user::$uid:$uid:$user:$path_access:/bin/sh" >> $FILE_Passwd
		    else
		    echo "$user::$uid:$uid:$user:/mnt:/bin/sh" >> $FILE_Passwd
		    fi
		    echo "$user:x:$uid:$user" >> $FILE_Group
		    if [ -f $USERLISTFD ];then
		    echo "$index:$user" >> $USERLISTFD
		    else
		    echo "$index:$user" > $USERLISTFD
		    fi
	    fi
	    chpasswd.sh "$user" "$passwd"
	fi
}

del_storage_user()
{
    if [ "$user" != "admin" ];then
        if [ -f $USERLISTFD ];then
            local indx=`sed -n /^${index}:/p $USERLISTFD | awk -F : '{print $1}'`
            local olduser=`sed -n /^${index}:/p $USERLISTFD | awk -F : '{print $2}'`
            if [ -n "$indx" ];then
            sed -i /^${indx}/d $USERLISTFD
            fi
            if [ -n "$olduser" ];then
            deluser "${olduser}"
            fi
        fi
    fi
}

case "$1" in
	"add")
	    del_storage_user
		add_storage_user
		;;
	"del")
	    del_storage_user
	    ;;
	*)
        echo "$0 add/del"
		;;
esac
