#!/bin/bash
OLDDIR=`pwd`
param0=$0
param0=${param0:2}
param0=${param0%1822_nic_collect.sh}
if [ param0 ];then
	PATH_SCRIPT="$OLDDIR/$param0"
else
	PATH_SCRIPT="$OLDDIR"
fi
#get system type
SYS_TYPE=`uname -i`
if [ "${SYS_TYPE}" == "aarch64" ]; then
 	    dir="aarch64"
elif [ "${SYS_TYPE}" == "x86_64" ]; then
  dir="x86_64"
else
 	    exit 1
fi
PATH_RESULT="$PATH_SCRIPT/collect_info"
OUTPUT="$PATH_SCRIPT/1822_nic_info.tar.gz"
SCRIPT_LOG="mezz.log"
TOOL_PATH="$PATH_SCRIPT/${dir}"
TMP_LOG="$PATH_SCRIPT/tmp.log"
NIC_LOG="$PATH_SCRIPT/hinic"

# Input: logfilename "text"
function log_info()
{
	LOGFILE="$1"
	if [ ! -f "$LOGFILE" ];
	then
		return 2
	fi
	shift
	echo "$@" >> "$LOGFILE" 2>&1
}

# Input: logfilename command; command is from os;
function log_cmd()
{
	LOGFILE=$PATH_SCRIPT/$1
	shift
	CMDLINE_ORIG="$@"
	CMDBIN=$(echo $CMDLINE_ORIG | awk '{print $1}')
	CMD=$(\which $CMDBIN | awk '{print $1}')
	echo "#==[ Command ]======================================#" >> $LOGFILE
	if [ -x "$CMD" ]; then
		CMDLINE=$(echo $CMDLINE_ORIG | sed -e "s!${CMDBIN}!${CMD}!")
		echo "# $CMDLINE" >> $LOGFILE
		$CMDLINE >> $LOGFILE 2>&1
		EXIT_STATUS=$?
	else
		echo "# $CMDLINE_ORIG" >> $LOGFILE
		echo "ERROR: $CMD Command not found or not executable"
		return 1
	fi
	
	usleep 10000
	echo >> $LOGFILE
	return $EXIT_STATUS
}

function fn_syslog()
{
    local msg_info=$1
    local log_level=$2
    local username=`id -nu` 
    
    if [ "$log_level" = "info" ]
    then 
        log_level="local0.info"
    else 
        log_level="local0.err"
    fi   
    
    logger -t "${username}" -p "${log_level}" "${msg_info}"
    
    return 0
}

function user_operate_log()
{
    local result_info=$1
    OPERIP=`who am i | awk '{print $NF}' | sed 's/[()]//g'`
    
    if [[ "$1" == "0" ]]; then
	    fn_syslog "collect_osta.sh;Successful;${OPERIP:-127.0.0.1};exec mezz_info.sh Successfully." "info"
    else
	    fn_syslog "collect_osta.sh;Failed;${OPERIP:-127.0.0.1};exec mezz_info.sh Failure."            
    fi
}

check_path_result()
{
	if [ -d $PATH_RESULT ]; then
		log_cmd $SCRIPT_LOG "chmod 600 $PATH_RESULT"
	else
		log_cmd $SCRIPT_LOG "mkdir -m 600 $PATH_RESULT"
	fi
}


change_result_competence()
{
	if [ -d $PATH_RESULT ];then
		log_cmd $SCRIPT_LOG "chmod -Rc 600 $PATH_RESULT"
	fi
}


collect_1822_log()
{
    if [ -f $TOOL_PATH/hinicadm ]; then
    	echo "$TOOL_PATH/hinicadm exists."
    else
    	echo "$TOOL_PATH/hinicadm is not exist"
        user_operate_log
        exit 1
    fi

    if [ -f hinic_fault_log_collect.sh ]; then
    	log_cmd $SCRIPT_LOG "chmod 550 hinic_fault_log_collect.sh"
    	./hinic_fault_log_collect.sh
    fi
}


cd $PATH_SCRIPT >> $TMP_LOG

check_path_result
change_result_competence
collect_1822_log
log_info $SCRIPT_LOG "1822 nic info collect success!"
user_operate_log 0

cd $PATH_SCRIPT >> $TMP_LOG
tar -czf $OUTPUT collect_info $SCRIPT_LOG hinic --format=gnu>> $TMP_LOG
rm -rf $NIC_LOG >> $TMP_LOG

cd $OLDDIR >> $TMP_LOG

