#! /bin/sh
#Function:add user
#Writer:liutiansi
#Mail:lliutiansi@gmail.com
#Date:2007-10-29 16:25

#参数文件及验证登录
source config
source checkonline

#返回子程序运行状态临时文件，0为失败，1为成功。
add_server_tempfile=`add_server_tempfile 2>/dev/null` || add_server_tempfile=/tmp/OPreturn$main_pid

#运行状态标记
returncode=0

#统计参数个数
checkkey=0

#根据$returncode的值判断是否退出或继续循环，=1 or =250时退出。
while test $returncode != 1 && test $returncode != 250
do
exec 3>&1

#弹出输入对话框
value=`dialog --ok-label "Add"  --colors --backtitle "$copyright_info" --title "$system_info" \
	 --form "\n\n请输入服务器信息："  \
	15 50 0 \
	"服务器名称：" 1 1 "" 1 13 12 0 \
	"服务器内IP："    3 1 ""  3 13 15 0 \
	"服务器外IP："    5 1 ""  5 13 15 0 \
2>&1 1>&3`

#获取输入对话框的运行结果值给returncode
returncode=$?
exec 3>&-
	#对returncode值进行选择分支，0为点击[OK]按钮；*为点击[Cancel]按钮或其它中断。
	case $returncode in
	0)
		#判断是否输完整信息;
		for vlist in $value
 		do
 			checkkey=`expr $checkkey + 1`
			str="$str""'$vlist',"
		done;
		
		#统计非空输入域小于3，则提示；
    if [ $checkkey -lt 3 ]; then
      outmessage="输入域不能为空，请重输！ "
      export outmessage
      msgbox
      #输出0标志到临时文件，代表失败；
			echo "0" > $add_server_tempfile			
    else 
    	#用,号分隔字符串，取第二列数；
			host=`echo "$str"|awk -F ',' '{print $2}'`
			
			#用'号分隔字符串，取第二列数；
			host=`echo "$host"|awk -F "'" '{print $2}'`
			intodbstr="$str""'$server_class_value'"
			exec 3>&1
			echo -n "【如果长时间没有反应，说明远程主机没有开放管理服务器的SSH权限，请检查远程主机！请按Ctrl+C结束。】"
			#传输公钥；
			scp -S sshto -i $sysadmin_path/identity $sysadmin_path/authorized_keys root@$host:~/.ssh/ 1>&3
			scpresult=$?
			exec 3>&1
			if [ $scpresult -eq 0 ]; then
				#更新数据库；
				result=`$mysql_bin -h $mysql_host -u$mysql_user -p$mysql_passwd -e "insert into sysadmin.ty_server("SERVERNAME","SERVER","SERVERIP","SERVERCLASS") values ("$intodbstr");" 2>&1`
				if [ $? -eq 0 ] && [ -z "$result" ]; then
          outmessage="$host服务器添加成功:)，请返回！ "
					export outmessage
					msgbox				
					echo "1" > $add_server_tempfile
				else
          outmessage="$host添加主机失败，错误信息：$result"
					export outmessage
					msgbox				
					echo "0" > $add_server_tempfile				
				fi
			else
        outmessage="添加主机$host失败，无法创建证书，原因可能是无法连接远程主机:(，请返回！ "
				export outmessage
				msgbox
				echo "0" > $add_server_tempfile
			fi
			
			result_up_str=$outmessage
			#写运行结果到日志；
			logs="[$(date +'%Y-%m-%d %H:%M:%S')]$result_up_str"
			RecordLog
		fi
		exit
		;;
	*)
		dialog \
     	--clear \
     	--title "$system_info" \
     	--yesno "\n\n确定要取消操作吗？" 10 30
     	case $? in
     	0)
					echo "1" > $add_server_tempfile
					break
					;;
     	1)
					returncode=99
					;;
		esac
		;;
	esac
done
