#!/bin/bash
# desc: 用户登录(检查用户是否存在,输入是否超过3次)
# author: 孙鑫
# time: 2018年2月19号
# version: v1.0
############检查用户是否存在#########
check_user(){
for a in `cat /server/script/shell/day1/pass.txt|awk '{print $1}'`
do
	if [ "$1" == "$a" ];then
		num_user=202
		break
	else
		num_user=200
		break
	fi
done
}
##############检查密码是否存在#######################
check_password(){
for b in `cat /server/script/shell/day1/pass.txt|awk '{print $2}'`	
do
	if [ "$1" == "$b" ];then
		num_password=302
		break
	else
		num_password=300
		break
	fi
done
}
#######查看密码文件是否存在,存在继续 不存在创建################
[ -f /server/script/shell/day1/pass.txt ] || mkdir -p /server/script/shell/day1/pass.txt
######程序开始################################
for i in {1,2,3}
do
	read -p "please insert username:" user
	check_user $user
	if [ $num_user -eq 202 ];then
		if [ "`awk '$1~/'"$user"'/{print $3}' /server/script/shell/day1/pass.txt`" == "fail" ];then
			echo "user is lock!!"
			exit
		else
			read -p "please insert password:" -s password
			check_password $password
			if [ $num_password -eq 302 ];then
				echo "welcome to shell world!!"
				break
			else
				if [ $i -eq 3 ];then
					sed -ri 's/('"$user"'.*)/\1 fail/g' /server/script/shell/day1/pass.txt
					echo "user is lock!!"
					exit
				fi
			fi
		fi	
	else		
		read -p "please insert password:" -s password
		echo "${user} ${password}" >>/server/script/shell/day1/pass.txt
		echo "welcome new_user to shell world!!"
		break	
	fi
	
done