#!/usr/bin/bash
#
# Copyright (c) 2006, 2025, Oracle and/or its affiliates.
#
# 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="[-a] [-v] [<label> ...]"

exec 3>/dev/null

help=
verbose=
version=
usage=
all=
while case "$#" in 0) break ;; esac
do
    case "$1" in
    -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
check_oracleasm_config

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

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

for d in "$@"
do
    case "$d" in
    */*)
        echo "Invalid disk name: \"${d}\"" | asm_log 1
        exit 1
        ;;
    *)
        ;;
    esac
done

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

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

to_clean "$@" | while read LINE
    do
        if [ "$all" != "t" ]
        then
            echo "Validating disk \"${LINE}\"" >&3
            INFO="$(oracleasm-read-label "$(asm_disk_path "${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 "${LINE}" 2>&3
        if [ $? != 0 ]
        then
            echo "Unable to clean disk \"${LINE}\"" | asm_log 1
        fi
    done

exit 0
