#!/bin/bash
#
#本脚本用于批量添加/删除用户,用户初始密码是123456,首次登陆需要修改密码
#格式:./class_stu.sh 参数1 参数2 参数3
# 参数1:起始用户名,为纯数字编号,长度必须大于6
# 参数2:添加人数[0-999]
# 参数3:操作:1-添加,2-删除
#例:./class_stu.sh 2009034201 30 1 表示添加从2009034201开始的30个帐号
#    ./class_stu.sh 2009034201 30 2 表示删除从2009034201开始的30个帐号   
#class_stu.sh
#2011-8-21 LOPN

export PATH=/bin:/sbin:/usr/bin:/usr/sbin

function error()
{
 echo "*****ERROR: the format is : ./class_stu.sh par1 par2 par3"
 echo "*****EXAMPLE:class_stu.sh 2009034201 30 1"
 echo "*****NOTICE:par1 must is number and the length must rather 6"
 echo "*****NOTICE:par2 meanings the number of you want add[0-999]"
 echo "*****NOTICE:par3 respect your choice-add or del:"
 echo "****   1:add memeber  ***********"
 echo "****   2:del memeber  ***********"
 echo "******************Other number is illegal********************"
 
}

if [ $# != 3 ]
then
 error
 exit 1
fi

reciveinit1=`echo $1 | grep -e "^[0-9]\{6,\}$"  `
reciveinit2=`echo $2 | grep -e "^[0-9]\{1,3\}$" `
operater=`echo $3 | grep -e "^[0-9]$"`  
if [ "$1" != "$reciveinit1" ] || [ "$2" != "$reciveinit2" ] || [ "$3" != $3 ]
then
 error
 exit 1
fi


initaccount=$1
curaccount=$initaccount
i=0

case $3 in
1)
 echo "***************************ADD USER********************************"
 echo -n "Are you ensure to add?[y|Y/n|N]"
 read yes
 if [ "$yes" == "y" -o "$yes" == "Y" ]
 then
  while [ "$i" != "$2" ]
  do
   echo "**********ADD USER $curaccount **********"
   ifexist=`cat /etc/passwd | awk -F : "{print \\$1}" | grep $curaccount`
   if [ "$ifexist" == "$curaccount" ]
   then
    echo "***********THE USER  $curaccount ALREADY EXISTS!*********"
    echo "********************NEXT*********************"
   else

    useradd $curaccount
    echo "123456" | passwd --stdin $curaccount
    chage -d 0 $curaccount
    echo "*******THE USER $curaccount HAS BEEN ADD ! OK***********"
   fi
   i=$(($i+1))
   curaccount=$(($curaccount+1))
  done
 fi
 ;;
2) 
 echo "***************************DEL USER********************************"
 echo -n "Are you ensure to del user?[y|Y/n|N]"
 read yes
 if [ "$yes" == "y" -o "$yes" == "Y" ]
 then
  while [ "$i" != "$2" ]
  do
   echo "*********************DEL USER $curaccount *********************"
   ifexist=`cat /etc/passwd | awk -F : "{print \\$1}" | grep $curaccount`
   if [ "$ifexist" == "$curaccount" ]
   then
    userdel -r $curaccount
    echo "******THE USER $curaccount HAS BEEN DELETED ! OK********" 
   else
    echo "************The USER $curaccount DOES NOT  EXISTS!***********"
    echo "***********************NEXT!*******************************"
   fi
   i=$(($i+1))
   curaccount=$(($curaccount+1))
  done
 fi
 ;;
*)
 echo "******************************NOTICE*****************************"
 echo "please see the notice clear"
 error
 ;;
esac

echo "***********************THE OPERATOR HAS BEEN FINISHED!************************"