#!/bin/bash
#
# Copyright (c) 2018, 2024, Oracle and/or its affiliates.
#
# Delete unused iid files under /dev/oracleasm/iid
#


# Force LC_ALL=C
export LC_ALL=C
 
USAGE="[-f][-l <manager>]"

exec 3>/dev/null

help=
usage=
force=
count=0
filename=

# Load configuration
. oracleasm-Xshlib

while case "$#" in 0) break ;; esac
do
    case "$1" in
    -l|--manager)
        case "$#" in 1) usage=t; break ;; esac
        shift
        ORACLE_ASMMANAGER="$1"
        ;;
    -f|--force)
        force=t
        ;;
    -h|--help)
        help=t
        ;;
    -*)
        usage=t
        ;;
    *)
        break
        ;;
    esac
    shift
done

if [ "$help" = "t" -o "$usage" = "t" ]
then
    usage
fi

# if ASM driver is not supported then this is a NOP
if [ "$ORACLEASM_DRIVER_SUPPORTED" = "false" ]
then
    exit 0
fi

if [ -z "$ORACLE_ASMMANAGER" ]
then
    ORACLE_ASMMANAGER="/dev/oracleasm"
fi
                                           
ORACLE_ASMMANAGERSEARCH="`echo $ORACLE_ASMMANAGER | sed -e 's/\//\\\\\//g'`"
grep "^oracleasmfs $ORACLE_ASMMANAGERSEARCH oracleasmfs" /proc/mounts >/dev/null 2>&1

STATUS2="$?"

if [ "$STATUS2" -ne  0 ]
then
	die "/dev/oracleasm is not mounted. Please use 'oracleasm init'"
fi

iid_path="${ORACLE_ASMMANAGER}/iid/"

delete_iids()
{
	while read filename ; 
	do
		if [ -z "$filename" ]
		then
			break
		fi		
		fuser -s "${iid_path}$filename" && continue 
		rm -f "${iid_path}$filename" 
		count=`expr $count + 1`
 
	done <<< "$(oracleasm-list-iids $iid_path)" 
}

if [ "$force" == "t" ]
then
	delete_iids 2>&3
	exit 0
fi

read -p "This command will delete unused iid files if any, Are you sure? (Y/N) " -n 1 -r
if [[ $REPLY =~ ^[Yy]$ ]]
then
	delete_iids 2>&3
	if [ "$count" != 0 ]
	then
		echo -e
		echo "Deleted $count unused iid files"
		exit 0
	fi
	echo -e
	echo "No unused iid files to delete"
fi

exit 0
