#!/bin/bash

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

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

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

date_str=$(date +%Y%m%d%H%M)
tmp_log_name="$(date +%Y%m%d%H%M)_log"

#exception handler
function exception_handler
{
	rm -rf /opt/hifc/$date_str
	rm -rf /opt/hifc/${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}/collect_log_prd.sh
if [[ $? -ne 0 ]]; then
	echo "ERROR: Collect log failed."
	delete_temp_tool
	exception_handler
fi

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

