#!/bin/bash

work_dir=$(dirname "$0")
#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
#check whether hinic driver is installed
is_hinic_installed=$(lsmod | grep hinic)
if [[ -z "$is_hinic_installed" ]]; then
	echo "ERROR: The hinic driver isn't installed."
	exit 1
fi

#check whether hinicadm is installed, if installed do nothing, if not installed install temporary
is_hinicadm_installed=$(whereis hinicadm | awk -F ":" '{print $2}')
if [[ -z "$is_hinicadm_installed" ]]; then
  echo "install hinicadm"
	chmod 550 $work_dir/${dir}/hinicadm
	cp $work_dir/${dir}/hinicadm  /usr/sbin/  2>/dev/null
fi

#if hinicadm not installed, remove temporary installed hinicadm
function delete_temp_tool
{
	if [[ -z "$is_hinicadm_installed" ]]; then
		rm /usr/sbin/hinicadm  2>/dev/null
	fi
}

date_str=$(date +%Y_%m_%d_%H_%M)
tmp_log_name="log_$date_str"

#exception handler
function exception_handler
{
	rm -rf /opt/hinic/$date_strls
	rm -rf /opt/hinic/${tmp_log_name}*
	rm -rf $work_dir/${tmp_log_name}*
	
	exit 1
}

#collect log, get log archive file name and get log archive
bash $work_dir/${dir}/hinic_log_collect.sh -a
if [[ $? -ne 137 ]]; then
	echo "ERROR: Collect log failed."
	delete_temp_tool
	exception_handler
fi

log_archive_name=$(ls /opt/hinic/ | grep -o ${tmp_log_name}.*)
#copy log archive
mv /opt/hinic $work_dir/
if [[ $? -ne 0 ]]; then
	echo "ERROR: Collect log failed. No log archive file generate."
	delete_temp_tool
	exception_handler
else
	echo "INFO: Collect log succeed. Log archive file is $work_dir/hinic"
fi
delete_temp_tool

