#!/bin/bash
#
# Drop ASM disks, either stale ones or all disks.  Stale cleanup is done
# during scandisks, all disks are dropped during shutdown.
#

# Force LC_ALL=C
export LC_ALL=C
 
USAGE="[-l <manager>] [-a] [-v] [<label> ...]"

exec 3>/dev/null

help=
verbose=
version=
usage=
all=
while case "$#" in 0) break ;; esac
do
    case "$1" in
    -l|--manager)
        case "$#" in 1) usage=t; break ;; esac
        shift
        ORACLE_ASMMANAGER="$1"
        ;;
    -a|--all)
        all=t
        ;;
    -v|--verbose)
        verbose=t
        exec 3>&2
        ;;
    -V|--version)
        version=t
        ;;
    -h|--help)
        help=t
        ;;
    -*)
        usage=t
        ;;
    *)
        break
        ;;
    esac
    shift
done

# Load configuration
. oracleasm-Xshlib

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

if [ "$version" = "t" ]
then
    version
fi

for d in "$@"
do
    case "$d" in
    */*)
        die "Invalid disk name: \"${d}\""
        ;;
    *)
        ;;
    esac
done

to_clean()
{
    if [ $# -gt 0 ]
    then
        for d in "$@"
        do
            upper_disk "$d"
        done
    else
        oracleasm-listdisks -l "${ORACLE_ASMMANAGER}" 2>&3
    fi
}

if [ "$all" = "t" ]
then
    echo "Dropping ASM disks... "
else
    echo "Cleaning any stale ASM disks..."
fi

to_clean "$@" | while read LINE
    do
        if [ "$all" != "t" ]
        then
            echo "Validating disk \"${LINE}\"" >&3
            INFO="$(oracleasm-read-label "$(asm_disk_path "${ORACLE_ASMMANAGER}" "${LINE}")" 2>&3)"
            if [ $? = 0 -a -n "$INFO" ]
            then
                LABEL="$(echo "$INFO" | cut -f1 -d:)"
                if [ "$LABEL" = "$LINE" ]
                then
                    continue
                fi
            fi
        fi 

        echo "Cleaning disk \"${LINE}\""
        oracleasm-clean-disk -l "${ORACLE_ASMMANAGER}" "${LINE}" 2>&3
        if [ $? != 0 ]
        then
            echo "Unable to clean disk \"${LINE}\"" >&2
        fi
    done

exit 0

