#!/bin/sh


GLOBAL_URL="https://sit-ai-home.gree.com/sit/gateway/log-uploader"
sdPid=0
webPid=0
webDmesgPID=0
webMsgPID=0
LOCK=0
LOCKFILE="/home/root/lockfile"
MAC=$(cat /sys/class/net/eth0/address | tr -d ':')
DATE_CMD="date +%Y%m%d%H%M%S"
SERVER_IP="ubuntu@123.207.253.115:/home/ubuntu/HostLog"
PUSH_CMD="sshpass -p 'Zwj123456' scp -o StrictHostKeyChecking=no /home/root/sdcard/dmesg.log $SERVER_IP/$MAC-$($DATE_CMD)-dmesg.log"
PUSHED=0

touch $LOCKFILE
trap 'rm -rf "$LOCKDIR"' EXIT
isSdCardMounting_Func() {
	sdCardPath=$(lsblk | grep mmcblk0p1 | awk {'print $7'})
#	echo "sdCardPath= $sdCardPath"
	if [ ! -z "$sdCardPath" ]; then
		if [ $sdCardPath == "/home/root/sdcard" ];then
#			echo "/home/root/sdcard is mount"
			:
		else
			mount /dev/mmcblk0p1 /home/root/sdcard
		fi
		return 0
	else
		return 1
	fi
}


syslog_post_to_sdCard_Func() {
	sdCardMountPath=/home/root/sdcard
	isSdCardMounting_Func
	if [ $? -eq 0 ]; then              
        	sysLogPath=$sdCardMountPath/dmesg$1.log                         
		sysMsgPath=$sdCardMountPath/messages$1.log
        	echo "SD card path is $sdCardPath,system log name $sysLogPath,system messages name $sysMsgPath"
		fileNum=$(expr $(ls $sysLogPath | wc -l) + $(ls $sysMsgPath | wc -l))
		echo "fileNum = $fileNum"
		if [ $fileNum -lt 0 ]; then
			if [ ! -f $sysLogPath ]; then
				echo "$sysLogPath isn't exist!"
				touch $sysLogPath
			fi
			if [ ! -f $sysMsgPath ]; then
                                echo "$sysMsgPath isn't exist!"
                                touch $sysMsgPath
                        fi
			#当SD card假挂载时，创建后无法查到文件则证明为假挂载，卸载后再挂载
			fileNum=$($(ls $sdCardMountPath | wc -l) + $(ls $sysMsgPath | wc -l))
			if [ $fileNum -eq 0 ]; then
				echo "the sd card is mounted failed , umount it!"
				umount sdCardMountPath
				mount /dev/mmcblk0p1 /home/root/sdcard
				return 1
			fi
		fi

       		#dmesg -w |grep -v "c_can_platform 481cc000.can can0" >> $sysLogPath &
		echo "############ log : $(date) ############################# " >> $sysLogPath
		echo "reset record:$(devmem2 0x44E00F08) " >> $sysLogPath
		devmem2 0x44E00F08 w 0x00000010
        	dmesg -w  >> $sysLogPath  & #执行将dmesg持续输出至sd卡
		echo "############ log : $(date) ############################# " >>  $sysMsgPath
		cat /var/log/messages >> $sysMsgPath && tail -f /var/log/messages >> $sysMsgPath & #持续将messages输出至sd卡
		return 0 
	else                                                   
        	echo "please insert the SDCard in the host!!!!"
		return 1
	fi
}

killSdCardLoggingTask_Fun() {
	dmesgPID=$(ps -ef|grep "dmesg -w" | grep -v "grep" | awk {'print $2'})
	messagesPID=$(ps -ef|grep "tail -f /var/log/messages" | grep -v "grep" | awk {'print $2'})
	if [ ! -z "$dmesgPID" ];then
		kill $dmesgPID
		echo "kill $dmesgPID"
	else
		echo "dmesg -w isn't exist!"
	fi

	if [ ! -z "$messagesPID" ];then
                kill $messagesPID
                echo "kill $messagesPID"
        else
                echo "tail -f /var/log/messages isn't exist!"
        fi

}

isSDcardLogging_Fun() {
	dmesgPID=$(ps -ef|grep "dmesg -w" | grep -v "grep" | awk {'print $2'})
        messagesPID=$(ps -ef|grep "tail -f /var/log/messages" | grep -v "grep" | awk {'print $2'})
	if [ ! -z "$dmesgPID" ] || [ ! -z "$messagesPID" ];then
                echo "SDCard system log is logging by pid:$dmesgPID"
		return 0
        else
                echo "SDCard system log is not logging!"
		return 1
        fi
}

isSDcardLoggingAll_Fun() {
        dmesgPID=$(ps -ef|grep "dmesg -w" | grep -v "grep" | awk {'print $2'})
        messagesPID=$(ps -ef|grep "tail -f /var/log/messages" | grep -v "grep" | awk {'print $2'})
        if [ ! -z "$dmesgPID" ] && [ ! -z "$messagesPID" ];then
               # echo "SDCard system log is logging all"
                return 0
        else
                echo "someone log is killed!"
                return 1
        fi
}

isConnectting() {
	URL_Check="$GLOBAL_URL/checkUpload"
	curl -s --head --request --connect-timeout 2 --max-time 2 GET  $URL_Check > /dev/null 2>&1
	ret=$?
	if [ "$ret" -eq 0 ]; then
		echo "It's connectting!"
		return 0
	else
		echo " No net :$ret"
		return 1
	fi
}

netWorkIsWork() {
	ret=1
	while [ $ret -eq 1 ]; do 
		ping -c 1 -w 2 www.baidu.com > /dev/null
		ret=$?
		echo "ret = $ret"
	done
	

}


webLog_Post(){
	local retry=0
	local result
	local data_str=$1
	{
		flock 200
		while true
		do
			echo "data:$data_str"
			result=$(curl -s   --connect-timeout 10 --max-time 2  --request POST --url https://sit-ai-home.gree.com/sit/gateway/log-uploader/putLogMessage --header 'content-type: application/json' --data "$data_str")
			echo "result:$result"
			if [[ "$result" == *"success"* ]]; then
				break
			else
				retry=$(($retry+1))
				echo "web log failed $?:$result,at $retry times!"
				if [ $retry -ge 5 ]; then
					break
				fi
			fi
			sleep 2
		done
		sleep 1
	} 200>"$LOCKFILE"
}
sdCardLoggingTask_Fun() {
	while true
	do
		#阻塞等待SD card 挂载
		isSdCardMounting_Func
		status=$?
		echo "status = $status"
		while [ "$status" -eq 1 ]
		do
			echo "no card mounting"
			sleep 1
			isSdCardMounting_Func
			status=$?
		done
		#启动SD卡记录
		isSDcardLogging_Fun #判断是否有SD卡记录运行
		if [ $? -eq 1 ];then
			echo "the sdcard logging isn't run! running it now!"
			syslog_post_to_sdCard_Func
			if [ $? -eq 1 ]; then
				echo "syslog_post_to_sdCard_Func running failed!"
				continue
			fi
		else
			echo "sdCard logging is running!"
			killSdCardLoggingTask_Fun	#有任务运行中，则杀掉后重启
			sleep 1
			syslog_post_to_sdCard_Func	#重启SD卡记录
			if [ $? -eq 1 ]; then
                                echo "syslog_post_to_sdCard_Func running failed!"
                                continue
                        fi
		fi	
		
		#阻塞监听SD卡变动
		while true;do
			isSdCardMounting_Func
			ret=$?
			if [ "$ret" -eq 1 ]; then
				echo "the card is unmount!"
				break
			fi
			isSDcardLoggingAll_Fun
			ret=$?
			if [ "$ret" -eq 1 ]; then
                                echo "someone be killed!"
                                break
                        fi
			sleep 5
		done
	done
}

webLogging_dmesg_Fun(){
	local data
	local temp=$(dmesg)
#	echo $temp | while read -r log_line
#	do
#		data="{\"mac\":\"$MAC\",\"message\":\"[dmesg]$log_line\"}"
#		webLog_Post "$data"
#	done	

	sudo dmesg -w | while read -r log_line
        do
		data="{\"mac\":\"$MAC\",\"message\":\"[dmesg][$(date)]$log_line\"}"
                webLog_Post "$data"
		sleep 1
        done

}
webLogging_messges_Fun(){
	local data
#	sudo cat /var/log/messages | while read -r log_line
#        do
#                data="{\"mac\":\"$MAC\",\"message\":\"[messages]$log_line\"}"
#                webLog_Post "$data"
#        done

        sudo tail -f /var/log/messages | while read -r log_line
        do
                data="{\"mac\":\"$MAC\",\"message\":\"[messages][$(date)]$log_line\"}"
                webLog_Post "$data"
        	sleep 1
	done
}
webLoggingTask_Fun() {

	#网络判断
	while true;do
		isConnectting
        	ret=$?
        	if [ "$ret" -eq 0 ]; then
                	echo "connectting.........."
                	break
              	fi
               	sleep 1
	done

	webLogging_dmesg_Fun &
	webDmesgPID=$!
	webLogging_messges_Fun &
	webMsgPID=$!
}

cleanup() {
	echo "kill sd pid :$sdPid"
	if [ $sdPid -ne 0 ]; then
		kill $sdPid
		wait $sdPid > /dev/null
		sdPid=0
	fi

#	echo "kill web pid :$webPid"
#	if [ $webPid -ne 0 ]; then
#		kill $webPid
#        	wait $webPid > /dev/null
#		webPid=0
#	fi	
#
#	echo "kill web pid :$webDmesgPID"
#	if [ $webDmesgPID -ne 0 ]; then
#        	kill $webDmesgPID
#        	wait $webDmesgPID > /dev/null
#		webDmesgPID=0
#	fi
#
#	echo "kill web pid :$webMsgPID"
#	if [ $webMsgPID -ne 0 ]; then
#       	kill $webMsgPID
#        	wait $webMsgPID > /dev/null
#		webMsgPID=0
#	fi
}

test_Func() {
	sudo cat /var/log/messages | while read -r log_line
        do
		echo "$log_line"
        done
	
	sudo tail -f /var/log/messages | while read -r log_line
	do
                echo "$log_line"
        done

}
file_backup_Fun() {
	
	local file_name=$1
	if [ -z $file_name ]; then
		echo "no name"
		return 1
	fi

	if [ ! -f $file_name ]; then
		echo "file :$file_name isn't exist!!"
		return 1
	fi

	size=$( expr $(du -m  $file_name | awk {'print $1'}) + 0)
	echo "$file_name size is $size!"
	if [ $size -ge 1024 ];then
		echo "file $file_name is more than $size, backup and clean it!"
		cp $file_name "$file_name-bk"
	       echo "" > $file_name
	fi
	return 0
}

uploadFileFunc() {
	netWorkIsWork
	fileName="/home/root/$MAC-$($DATE_CMD)-dmesg.tar.gz"
        echo "package $fileName "
        tar -czf  $fileName /home/root/sdcard/dmesg.log
        sshpass -p 'Zwj123456' scp -o StrictHostKeyChecking=no $fileName  $SERVER_IP
	echo "upload done!"
	#rm $fileName
	rm /home/root/*-dmesg.tar.gz
}

cat <<EOF
###################################################################
	这是一个用于抓取主机系统日志到SD卡与web端的脚本！！！
###################################################################
EOF


echo "后台启动SD卡日志记录任务"
sdCardLoggingTask_Fun &
sdPid=$!
echo "run sd logging, pid : $sdPid"
#echo "后台启动web日志记录"
#webLoggingTask_Fun &
#webPid=$!
#echo "run web logging, pid : $webPid"
trap cleanup EXIT
cat /dev/watchdog0
while true
do
	file_backup_Fun /home/root/sdcard/dmesg.log
	file_backup_Fun /home/root/sdcard/messages.log
	echo "1" > /dev/watchdog0 >/dev/null 2>&1
	sleep 30
	if [ $PUSHED == "0" ]; then
		PUSHED=1
		chmod +x /usr/bin/sshpass
		uploadFileFunc &
	fi
done
wait
echo "log shell done!!!!!!!!!!!!!!"
