#!/bin/bash
# License: GPL
# Author: Steven Shiau <steven _at_ clonezilla org>
# Description: Program to purge the MDRAID layout.
# This file contains code generated by Google's Gemini. 

#
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

# Load the config in ocs-live.conf. This is specially for Clonezilla live. It will overwrite some settings of /etc/drbl/drbl-ocs.conf, such as $DIA...
[ -e "/etc/ocs/ocs-live.conf" ] && . /etc/ocs/ocs-live.conf

#
USAGE() {
    echo "$ocs - To purge the MDRAID layout interactively"
    echo "Usage:"
    echo "To run $ocs:"
    echo "$ocs"
    echo
} # end of USAGE

####################
### Main program ###
####################
check_if_root
ask_and_load_lang_set

echo $msg_delimiter_star_line
echo "INTERACTIVE ADVANCED WIPE SCRIPT (RAID 0/1/4/5/6/10)"
echo "You will be prompted to confirm the destruction of EACH device."
echo $msg_delimiter_star_line
read -p "Press Enter to begin analyzing devices, or Ctrl+C to abort..." dummy

if [ "$EUID" -ne 0 ]; then
  echo "Please run this script as root (e.g., sudo bash script.sh)."
  exit 1
fi

MD_DEVICES=$(awk '/^md/ {print $1}' /proc/mdstat 2>/dev/null)
declare -A PARENT_DISKS_TO_WIPE

echo ""
echo $msg_delimiter_star_line
echo "PHASE 1: MDRAID ARRAYS"
echo $msg_delimiter_star_line

if [ -n "$MD_DEVICES" ]; then
    for MD in $MD_DEVICES; do
        MD_PATH="/dev/$MD"
        echo $msg_delimiter_star_line
        echo "Found Array: $MD_PATH"
        
        # Show what is currently on this array
        echo "Current Layout:"
        lsblk "$MD_PATH" 2>/dev/null | sed 's/^/  /'
        echo $msg_delimiter_star_line

        # 1. Advanced Member Extraction
        MEMBERS=$(mdadm --detail "$MD_PATH" 2>/dev/null | awk '/^[ \t]*[0-9]+[ \t]+[0-9]+[ \t]+[0-9]+[ \t]+[0-9]+/ {
            if ($NF !~ /removed|missing/) {
                print $NF
            }
        }')
        
        # INTERACTIVE PROMPT
        read -p "⚠️  Do you want to STOP and DESTROY array $MD_PATH? [y/N]: " ans
        if [[ ! "$ans" =~ ^[Yy]$ ]]; then
            echo "   -> Skipping array $MD_PATH."
            continue
        fi

        echo "   -> Proceeding to wipe $MD_PATH..."

        # Add parents to the wipe list ONLY because the user confirmed array destruction
        for MEMBER in $MEMBERS; do
            if [ ! -b "$MEMBER" ]; then
                continue
            fi
            
            MEMBER_NAME=$(basename "$MEMBER")
            if [ -L "/sys/class/block/$MEMBER_NAME" ]; then
                PARENT_SYSFS=$(readlink -f "/sys/class/block/$MEMBER_NAME/..")
                PARENT_KNAME=$(basename "$PARENT_SYSFS")
                
                if [ -f "/sys/class/block/$PARENT_KNAME/dev" ]; then
                    PARENT_PATH="/dev/$PARENT_KNAME"
                    PARENT_DISKS_TO_WIPE["$PARENT_PATH"]=1
                fi
            fi
        done

        # 2. Unmount virtual MD sub-partitions
        MOUNTED_PARTS=$(lsblk -rn -o NAME,MOUNTPOINT "$MD_PATH" | awk '$2 != "" {print "/dev/"$1}')
        for MNT in $MOUNTED_PARTS; do
            umount -f "$MNT" 2>/dev/null || true
        done

        # 3. Wipe file system signatures on MD sub-partitions (e.g., md127p2)
        MD_SUBPARTS=$(lsblk -rn -o NAME "$MD_PATH" | grep -v "^$(basename $MD_PATH)$" | awk '{print "/dev/"$1}')
        for SUBPART in $(echo "$MD_SUBPARTS" | sort -r); do
            if [ -b "$SUBPART" ]; then
                wipefs -a "$SUBPART" 2>/dev/null || true
            fi
        done

        # 4. Stop the MD array
        mdadm --stop "$MD_PATH" || true

        # 5. Zero the RAID superblocks on the member partitions (e.g., nvme0n1p2)
        for MEMBER in $MEMBERS; do
            if [ -b "$MEMBER" ]; then
                mdadm --zero-superblock "$MEMBER" 2>/dev/null || true
            fi
        done
        
        echo "   -> Array $MD_PATH successfully destroyed."
    done
else
    [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
    echo "No active MDRAID devices found. Moving to physical disks."
    [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
fi

echo ""
echo $msg_delimiter_star_line
echo "PHASE 2: PHYSICAL DISKS"
echo $msg_delimiter_star_line

if [ ${#PARENT_DISKS_TO_WIPE[@]} -eq 0 ]; then
    [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
    echo "No physical disks were marked for wiping (either none exist, or you skipped the arrays above)."
    [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
else
    for DISK in "${!PARENT_DISKS_TO_WIPE[@]}"; do
        if [ -b "$DISK" ]; then
            echo $msg_delimiter_star_line
            echo "Found Physical Disk: $DISK"
            echo "Current Layout:"
            lsblk "$DISK" 2>/dev/null | sed 's/^/  /'
            echo $msg_delimiter_star_line
            
            # INTERACTIVE PROMPT
            read -p "⚠️  Do you want to WIPE ALL DATA and PARTITION TABLES on $DISK? [y/N]: " ans
            if [[ ! "$ans" =~ ^[Yy]$ ]]; then
                echo "   -> Skipping physical disk $DISK."
                continue
            fi
            
            echo "   -> Wiping $DISK..."
            
            MOUNTED_PHYS=$(lsblk -rn -o NAME,MOUNTPOINT "$DISK" | awk '$2 != "" {print "/dev/"$1}')
            for MNT in $MOUNTED_PHYS; do
                umount -f "$MNT" 2>/dev/null || true
            done

            DISK_NAME=$(basename "$DISK")
            DISK_PARTS=$(lsblk -rn -o NAME "$DISK" | grep -v "^${DISK_NAME}$" | awk '{print "/dev/"$1}')
            
            for PART in $(echo "$DISK_PARTS" | sort -r); do
                if [ -b "$PART" ]; then
                    wipefs -a "$PART" 2>/dev/null || true
                fi
            done
            
            wipefs -a "$DISK" 2>/dev/null || true
            
            dd if=/dev/zero of="$DISK" bs=1M count=10 status=none
            
            DISK_SIZE=$(blockdev --getsz "$DISK")
            if [ "$DISK_SIZE" -gt 20480 ]; then
                SEEK_POINT=$((DISK_SIZE - 20480))
                dd if=/dev/zero of="$DISK" bs=512 seek="$SEEK_POINT" count=20480 status=none
            fi
            
            partprobe "$DISK" 2>/dev/null || true
            echo "   -> $DISK is now completely clean."
        fi
    done
fi

echo $msg_delimiter_star_line
echo "Interactive cleanup complete."
echo $msg_delimiter_star_line
