#!/bin/bash
export PATH=/bin:/sbin:/usr/bin:/usr/sbin:$PATH

UCRYPT_PATH="/opt/ucrypt"
LOG_PATH="$UCRYPT_PATH/usb_crypt.log"

JSON_RECORD='['
## 获取当前插入电脑的usb存储设备

if [[ ! -d "$UCRYPT_PATH" ]]; then 
	mkdir -p $UCRYPT_PATH
fi

#if device add, it well add one record; as the same about remove , so if one device have odd record, it meaning that it has add havn't remove,
function get_odd_device {
	if [[ ! -f $LOG_PATH ]]; then
		return 
	fi
	cat $LOG_PATH | awk '{print $3}' | sort | uniq #-c | awk '{A=($1%2); if(A!=0) print $2}' 
}

function json_record {
	if [[ $# -ne 8 ]]; then
		return 0
	fi
	JSON_RECORD="$JSON_RECORD{\"device\":\"$3\", \"flag\":\"$2\",\"uuid\":\"$4\",\"size\": \"$5\", \"secret_code\":\"$6\", \"person\":\"$7\", \"person_code\":\"$8\"}, "
}

function resolve_log {
	for DEV in `get_odd_device`; do 
		# get the $DEV new log
		RECORD=`cat $LOG_PATH | grep -w $DEV | tail -n 1 | awk '{if($1==1) print}'` 
		json_record $RECORD
	done
	JSON_RECORD=${JSON_RECORD%,*}
	JSON_RECORD="$JSON_RECORD]"
	echo $JSON_RECORD >"$UCRYPT_PATH/usb_crypt_shell"
}

resolve_log

