#!/bin/sh
CORE_ROOT=/
CORE_FILES_DIR=core_files
MNT_DIR=mnt
PATH=/bin:/usr/bin:
# export ROLE_ID="root"

checkResult() {
	case $ftpResult in
0)	printf "Files transferred successfully!\n"
	exit
	;;
1)	printf "Could not connect to remote host.\n"
	;;
2)	printf "Could not connect to remote host - timed out.\n"
	;;
3)	printf "Transfer Failed!\n"
	;;
4)	printf "Transfer Failed - Timed out.\n"
	;;
5)	printf "Directory change failed.\n"
	;;
6)	printf "Directory change failed - timed out.\n"
	;;
7)	printf "Malformed URL.\n"
	;;
8)	printf "Useage Error.\n"
	;;
9)	printf "Error in login configuration file\n"
	;;
10)	printf "Library initialization failed.\n"
	;;
11)	printf "Session initialization failed.\n"
	;;
*)	printf "NCFTP Failed (%d)!\n" $ftpResult
	;;

	esac
}

# this routine checks if the given argument is a core file directory
NON_EXISTANT1="\/tmp\/not\/a\/file \/here\/"
NON_EXISTANT2="/tmp/not/a/file /here/"
isCoreFile() {
	tmpStr="$1"
	if [ -z "$tmpStr" ]
	then
		# NULL is not a valid core file
		return 0
	fi
	if [ "$tmpStr" == "/core_files/" ]
	then
		# can't give the while directory
		return 0
	fi
	if [ "$tmpStr" == "/mnt/core_files/" ]
	then
		# can't give the while directory
		return 0
	fi
	tmprv=`echo $tmpStr | /bin/sed -e "s/^\/core_files\//${NON_EXISTANT1}/"`
	echo $tmprv | grep "${NON_EXISTANT2}" > /dev/null
	if [ $? -eq 0 ]
	then
		return 1
	fi
	tmprv=`echo $tmpStr | /bin/sed -e "s/^\/mnt\/core_files\//${NON_EXISTANT1}/"`
	echo $tmprv | grep "${NON_EXISTANT2}" > /dev/null
	if [ $? -eq 0 ]
	then
		return 1
	fi
	# Not a kind of file that we are intrested
	return 0
}
RemoveFilesSafe() {
	rmElem="$1"
	if [ -z "$rmElem" ]
	then
		printf "PANIC: trying to remove from root dir!\n"
		exit -1
	else
		ls ${rmElem}/* > /dev/null 2>&1
		if [ $? -eq 0 ]
		then
			printf "Removing: %s\n" "$rmElem"
			rm ${rmElem}/*
		else
			printf "No core or FFDC data files found under: ${rmElem}\n"
		fi
	fi
}
rmCoreFilesListGiven() {
	markedFiles=0
	idx=0
	rmFileList=" "

	#Make sure user has permissions to remove the files
	if [ -f /fabos/libexec/rbac_check ]; then 
		/fabos/libexec/rbac_check -opt `/bin/basename $0` -r
	fi
	if [ $? -ne 0 ]; then
		printf "Cannot remove core files.\n"
		exit -1
	fi

	tmplist1=`printf "${argRemoveFileList}" | tr "," -t " "`
	for tmpfile in ${tmplist1}
	do
		isCoreFile $tmpfile
		if [ $? -ne 1 -o ! -d "$tmpfile" ]
		then
			printf "Omitting invalid file directory: %s\n" $tmpfile
		else
			rmFileList="${rmFileList} ${tmpfile} "
			RemoveFilesSafe $tmpfile
		fi
		if [ "$tmpStr" == "/core_files/ffdc_data" ]
		then
		#printf "reset fddc control count"
		/fabos/sbin/supportuffdc -p
		fi
	done
}

# Function to remove marked core files
rmCoreFilesListMarked() {
	markedFiles=0
	idx=0

	#Make sure user has permissions to remove the files
        if [ -f /fabos/libexec/rbac_check ]; then
		/fabos/libexec/rbac_check -opt `/bin/basename $0` -r
	fi
	if [ $? -ne 0 ]; then
		printf "Cannot remove core files.\n"
		exit -1
	fi

	while [ $idx -lt $coreFilesCount ]
	do
		if [ "${coreSelArry[${idx}]}" = "*" ]
		then
			printf "removing core or FFDC data files under: %s\n" ${coreFileArry[$idx]}
			/bin/rm -f  ${coreFileArry[$idx]}/*
			markedFiles=`/usr/bin/expr ${markedFiles} + 1`
			if [ "${coreFileArry[$idx]}" == "/core_files/ffdc_data" ]
			then
			      #printf "reset fddc control count"
			      /fabos/sbin/supportuffdc -p
			fi
		        # for fdet and ptlog in /core_files/
			name=${coreFileArry[$idx]:12:5}
		        # for fdet and ptlog in /mnt/core_files/
			name1=${coreFileArry[$idx]:16:5}
			if [ "$name" = "fdet." -o "$name" = "ptlog" ] ||
		           [ "$name1" = "fdet." -o "$name1" = "ptlog" ]
			then
				/bin/rmdir ${coreFileArry[$idx]}
			fi
		fi
		idx=`/usr/bin/expr ${idx} + 1`
	done
}

# Function to list a list of marked core files only
listCoreFilesListMarked() {
	markedFiles=0
	idx=0
	while [ $idx -lt $coreFilesCount ]
	do
		if [  "${coreSelArry[${idx}]}" = "*" ]
		then
			printf "	%s\n" ${coreFileArry[$idx]}
			markedFiles=`/usr/bin/expr ${markedFiles} + 1`
		fi
		idx=`/usr/bin/expr ${idx} + 1`
	done
}

# Function to remove ALL core files
rmCoreFilesListAll() {
	idx=0

	#Make sure user has permissions to remove the files
        if [ -f /fabos/libexec/rbac_check ]; then
		/fabos/libexec/rbac_check -opt `/bin/basename $0` -r
	fi
	if [ $? -ne 0 ]; then
		printf "Cannot remove core files.\n"
		exit -1
	fi

	while [ $idx -lt $coreFilesCount ]
	do
		printf " removing files under: %s\n" ${coreFileArry[$idx]}
		/bin/rm -f ${coreFileArry[$idx]}/*
		# for fdet and ptlog in /core_files/
		name=${coreFileArry[$idx]:12:5}
		# for fdet and ptlog in /mnt/core_files/
		name1=${coreFileArry[$idx]:16:5}
		if [ "$name" = "fdet." -o "$name" = "ptlog" ] ||
		   [ "$name1" = "fdet." -o "$name1" = "ptlog" ]
		then
			/bin/rmdir ${coreFileArry[$idx]}
		fi
		idx=`/usr/bin/expr ${idx} + 1`
	done
	#printf "reset fddc control count"
	/fabos/sbin/supportuffdc -p

}

# Function to list ALL core files (without marks)
listCoreFilesListAll() {
	idx=0
	while [ $idx -lt $coreFilesCount ]
	do
		printf "	%s\n" ${coreFileArry[$idx]}
		idx=`/usr/bin/expr ${idx} + 1`
	done
}

# Function to list a list of core files with marks
listCoreFilesList() {
	if [ $coreFilesCount -eq 0 ]
	then
		printf "No core or FFDC data files found!\n"
		exit
	fi
	printf "following %d directories contains core or FFDC data files:\n" $coreFilesCount
	idx=0
	while [ $idx -lt $coreFilesCount ]
	do
		printf "	[%s]%d: %s\n" "${coreSelArry[${idx}]}" $idx ${coreFileArry[$idx]}
		idx=`/usr/bin/expr ${idx} + 1`
	done
}

# Function to get a list of core files
getCoreFileList() {
	core_files_list=`/usr/bin/find ${CORE_ROOT}${CORE_FILES_DIR} ${CORE_ROOT}${MNT_DIR}/${CORE_FILES_DIR} \( -name "*ffdc*" -o -name "*core*" \) -type f -print 2> /dev/null`
	
	if [ -z "${core_files_list}" ]
	then
		printf "No core or FFDC data files found!\n"
		exit
	fi
	tmpList=""
	for coreFile in ${core_files_list}
	do
		tmpList="${tmpList}  `/usr/bin/dirname ${coreFile}`"
	done
	core_files_list=`/bin/ls -d $tmpList | /bin/sort | /usr/bin/uniq`
	idx=0
	for coreFile in ${core_files_list}
	do
		coreFileArry[${idx}]="${coreFile}"
		coreSelArry[${idx}]=" "
		idx=`/usr/bin/expr ${idx} + 1`
	done
	coreFilesCount=$idx
}
printUsage() {
	printf "
	usage:
To enter into interactive mode:-
	`/bin/basename $0`

To list all the core files:-
	`/bin/basename $0` -l 

To remove corefiles under a daemon's directory, <dir-name>:-
	`/bin/basename $0` -r <dir-name>

To remove ALL corefiles (in / and /mnt)
	`/bin/basename $0` -R

"
}
# function to just list files on the terminal
listAllFiles() {
	rv=`find /core_files/*/ /mnt/core_files/*/ -type f -print | wc -l |
sed -e 's/[ \t]//g'`
	if [ $rv -lt 1 ]
	then
		printf "No core or FFDC data files found!\n"
		exit 0
	fi
	find /core_files/*/ /mnt/core_files/*/ -type f -print
}

#Clearing the core_files in both the partitions.
FipsZeroizeCore() {

    /bin/dd if=/dev/urandom of=$FIPS_TEMP_FILE count=512 >/dev/NULL 2>&1
    /usr/bin/find /core_files/ \( -name "*ffdc*" -o -name "*core*" \) -type f -print  2> /dev/null |
        while read FILE; do
            /bin/cat $FIPS_TEMP_FILE > $FILE
            /bin/rm -f $FILE
        done
    /bin/rm -f $FIPS_TEMP_FILE

}

# main starts here
	argListFilesOnly=0	# Just list the core files  (-l)
	argRemoveFileList=""	# Remove these files	    (-r)
	argRemoveAll=0	    	# Remove ALL core files	    (-R)
	argrFlag=0		# local flag for -r
	argfFlag=0		# local flag for -f
	argYes=0    # Force "Yes" answers to all questions automatically (-y)
	argFipsZeroize=0	# Need to zeroize the core files (-Z)

	FIPS_TEMP_FILE="/tmp/fips_temp_file"

# get the command options, if any
	while getopts h:u:p:d:r:f:lRFaZ c
	do
		case $c in
		l) argListFilesOnly=1
		   ;;
		r) argRemoveFileList="${argRemoveFileList},${OPTARG}"
		   argrFlag=1;
		   ;;
		R) argRemoveAll=1
		   ;;
#		y) argYes=1
#		   ;;
		Z) argFipsZeroize=1
			;;
		*)
		   printUsage
		   exit -1
		   ;;
		esac
	done

	#Zeroize the core files for FIPS
	if [ $argFipsZeroize -eq 1 ]; then
		export -f FipsZeroizeCore
		export FIPS_TEMP_FILE
		/usr/sbin/chroot / bash -c "FipsZeroizeCore"
		/usr/sbin/chroot /mnt bash -c "FipsZeroizeCore"
		exit 0
	fi

	# user must be entitled to list files core files in order to run this command
        if [ -f /fabos/libexec/rbac_check ]; then
		/fabos/libexec/rbac_check -opt `/bin/basename $0` -l
	fi
	if [ $? -ne 0 ]; then
		exit -1
	fi

	chkExcl=`expr  \( $argRemoveAll + $argrFlag + $argListFilesOnly \) `
	if [ $chkExcl -gt 1 ]
	then
		printf "options  -r,  -R are mutually exclusive!\n"
		printUsage
		exit -1
	fi

# Let us do the work
# get a snap shot of the available core files, if anything is created
# latter, we don't consider them at this run
getCoreFileList

	# List files only
	if [ $argListFilesOnly -eq 1 ]
	then
		listAllFiles
		exit 0
	fi

	# Remove all Files
	if [  $argRemoveAll -eq 1 ]
	then
		rmCoreFilesListAll
		
		exit 0
	fi

	# remove given list files only
	if [ -n "$argRemoveFileList" ]
	then
		rmCoreFilesListGiven
		exit 0
	fi
#
# go to interactive mode
#


# keep bugging the user untils we transfer successfully or
# he decides to quit
while [ 1 ]
do
listCoreFilesList
printf "
	Welcome to core and FFDC data files management utility.

	Menu
	1(or R): Remove all files
	2(or r): Remove marked files
	3(or m): Mark Files for action
	4(or u): Un Mark Files for action
	5(or e): Exit

Your choice: "
read choice
case $choice in
3|m)
	printf "Enter File Number to mark: "
	read choice
	if [ -z "$choice" ]
	then
		choice=invalid
	fi
	nchoice=`echo $choice | /usr/bin/tr -cd "[0-9]\n"`
	if [ "$nchoice" != "$choice" ]
	then
		printf "Please enter a number\n"
	else
		if [ $nchoice -lt 0 -o $nchoice -ge $coreFilesCount ]
		then
			if [ $coreFilesCount -eq 1 ]
			then
				printf "Invalid Entry! Only 0 (zero) is allowed!\n"
			else
				printf "Please enter an inclusive number between 0 and `/usr/bin/expr $coreFilesCount - 1`\n"
			fi
		else
			coreSelArry[$nchoice]="*"
		fi
	fi
	;;
4|u)
	printf "Enter File Number to un mark: "
	read choice
	if [ -z "$choice" ]
	then
		choice=invalid
	fi
	nchoice=`echo $choice | /usr/bin/tr -cd "[0-9]\n"`
	if [ "$nchoice" != "$choice" ]
	then
		printf "Please enter a number\n"
	else
		if [ $nchoice -lt 0 -o $nchoice -ge $coreFilesCount ]
		then
			if [ $coreFilesCount -eq 1 ]
			then
				printf "Invalid Entry! Only 0 (zero) is allowed!\n"
			else
				printf "Please enter an inclusive number between 0 and `/usr/bin/expr $coreFilesCount - 1`\n"
			fi
		else
			coreSelArry[$nchoice]=" "
		fi
	fi
	;;
1|R)
	# Remove ALL core files

	# let us give them a list of ALL core files
	listCoreFilesListAll

	printf "
	You have opted to remove ALL files:-\n"
	printf "Please confirm (Y/[N]): "
	read choice
	if [ X${choice} = Xy -o X${choice} = XY -o X${choice} = \
	  Xyes -o X${choice} = XYES ] 
then
	printf "Removing files....\n"
	rmCoreFilesListAll
	printf "Done!\n"
	exit
else
	printf "files NOT removed\n"
fi
	exit
	;;
2|r)
	# Remove Marked files only

	# let us give them a list files what they marked
	listCoreFilesListMarked
	if [ $markedFiles -gt 0 ]
	then
		printf "
		You have opted to remove files under these directories:-\n"
		printf "Please confirm (Y/[N]): "
		read choice
		if [ X${choice} = Xy -o X${choice} = XY -o X${choice} = \
	  	Xyes -o X${choice} = XYES ] 
		then
			printf "Removing files....\n"
			rmCoreFilesListMarked
			printf "Done!\n"
			exit
		else
			printf "files NOT removed\n"
		fi
	else
		printf "No files marked\n"
	fi
	;;
5|e)
	exit
	;;
*)
	printf "Invalid choice\n"
	;;
esac
printf "Enter CR To Continue.... "
read choice
printf "\n\n\n\n\n\n"
done # main while
