#!/bin/bash
# License: GPL
# Author: Steven Shiau <steven _at_ clonezilla org>
# Description: Program to safely stop all active and inactive MDRAID devices
# Modeled after Clonezilla's ocs-lvm2-stop

DRBL_SCRIPT_PATH="${DRBL_SCRIPT_PATH:-/usr/share/drbl}"
. $DRBL_SCRIPT_PATH/sbin/drbl-conf-functions
. /etc/drbl/drbl-ocs.conf
. $DRBL_SCRIPT_PATH/sbin/ocs-functions

target_devs="$(echo "$*" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')"

if type mdadm &>/dev/null && [ -f /proc/mdstat ]; then
    echo "Shutting down the Software RAID (MDRAID) devices"

    # Parse /proc/mdstat to find ALL md devices (active or inactive)
    ACTIVE_MDS=$(awk '/^md/ {print $1}' /proc/mdstat 2>/dev/null | sort -r)

    for md in $ACTIVE_MDS; do
        if [ -n "$target_devs" ]; then
            md_matched="no"
            # Stop array if its underlying member devices are in target_devs
            members="$(mdadm --detail "/dev/$md" 2>/dev/null | awk '/^[ \t]*[0-9]+[ \t]+[0-9]+[ \t]+[0-9]+/ {print $NF}')"
            for mm in $members; do
                [ "$mm" = "missing" ] && continue
                mm_kname="$(basename "$mm")"
                mm_disk="$(get_diskname "$mm_kname")"
                for tdev in $target_devs; do
                    tdev="${tdev#/dev/}"
                    if [ "$mm_disk" = "$tdev" ] || [ "$mm_kname" = "$tdev" ]; then
                        md_matched="yes"
                        break 2
                    fi
                done
            done
            if [ "$md_matched" = "no" ]; then
                continue
            fi
        fi

        # If the device or any of its partitions is mounted (e.g. as image repository), skip stopping it
        if grep -qE "^/dev/${md}(p[0-9]+)?[[:space:]]" /proc/mounts 2>/dev/null; then
            echo "  Skipping mounted MDRAID device: /dev/$md"
            continue
        fi
        echo "  Shutting Down MDRAID device: /dev/$md "
        # If the device is busy (e.g. mounted), mdadm will exit with an error
        # and leave the array running to prevent system crash.
        mdadm --stop /dev/$md >/dev/null 2>&1
        
        if [ "$?" -ne 0 ]; then
            echo "  Unable to shutdown: /dev/$md (Device or resource busy)"
        fi
    done
    
    echo "Finished Shutting down the Software RAID (MDRAID) devices"
fi
