#!/bin/bash
# License: GPL
# Author: Steven Shiau <steven _at_ clonezilla org>
# Description: Program to scan and start MDRAID devices (Linux Software RAID)
# Modeled after Clonezilla's ocs-lvm2-start

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 live configuration if present
[ -e "/etc/ocs/ocs-live.conf" ] && . /etc/ocs/ocs-live.conf

# Default configurations
enable_mdraid="${enable_mdraid:-auto}"
mdraid_assemble_timeout="${mdraid_assemble_timeout:-15}"
cmdl_file="${cmdl_file:-/proc/cmdline}"
proc_mdstat="${proc_mdstat:-/proc/mdstat}"

force_run="no"
while [ $# -gt 0 ]; do
  case "$1" in
    -f|--force)
      force_run="yes"
      shift
      ;;
    -h|--help)
      echo "Usage: $(basename $0) [OPTION]"
      echo "Scan and assemble Linux Software RAID (MDRAID) devices."
      echo "Options:"
      echo "  -f, --force    Force scanning and assembly even if already run or cached."
      echo "  -h, --help     Display this help message and exit."
      exit 0
      ;;
    *)
      shift
      ;;
  esac
done

# State caching directory and flag
state_dir="${OCS_MDRAID_STATE_DIR:-/var/lib/clonezilla}"
[ ! -d "$state_dir" ] && mkdir -p "$state_dir" 2>/dev/null
[ ! -w "$state_dir" ] && state_dir="/tmp"
cache_file="$state_dir/ocs-mdraid-started"

# Check if MDRAID is explicitly disabled via boot parameters or configuration
# Supported boot parameters: ocs_mdraid=no/0/false/disable, skip_mdraid, nomd, nodmraid
cmdline_disabled="no"
if [ -f "$cmdl_file" ]; then
  if grep -qEw "(ocs_mdraid=(no|0|false|off|disable)|skip_mdraid|nomd|nodmraid)" "$cmdl_file" 2>/dev/null; then
    cmdline_disabled="yes"
  fi
fi

if [ "$cmdline_disabled" = "yes" ] || \
   [ "$ocs_mdraid" = "no" ] || [ "$ocs_mdraid" = "0" ] || [ "$ocs_mdraid" = "false" ] || [ "$ocs_mdraid" = "disable" ] || [ "$ocs_mdraid" = "off" ] || \
   [ "$enable_mdraid" = "no" ] || [ "$enable_mdraid" = "disable" ] || [ "$enable_mdraid" = "off" ]; then
  echo "Linux Software RAID (MDRAID) is disabled. Skipping MDRAID setup."
  touch "$cache_file" 2>/dev/null || true
  exit 0
fi

# Run-once guard: avoid redundant scanning across boot, repo setup, and imaging phases
if [ "$force_run" != "yes" ] && [ -f "$cache_file" ]; then
  exit 0
fi

# Function to check whether any MDRAID array or member partition exists on the system
is_any_mdraid_detected() {
  # 1. Existing active arrays in mdstat
  if [ -f "$proc_mdstat" ] && grep -q "^md" "$proc_mdstat" 2>/dev/null; then
    return 0
  fi
  # 2. Check blkid cache or query
  if type blkid &>/dev/null; then
    if blkid -t TYPE=linux_raid_member &>/dev/null || \
       blkid -t TYPE=isw_raid_member &>/dev/null || \
       blkid -t TYPE=ddf_raid_member &>/dev/null; then
      return 0
    fi
  fi
  # 3. Check lsblk filesystem types
  if type lsblk &>/dev/null; then
    if lsblk -dno FSTYPE 2>/dev/null | grep -qE "^(linux_raid_member|isw_raid_member|ddf_raid_member)$"; then
      return 0
    fi
  fi
  # 4. Check for arrays defined in mdadm.conf
  for conf in /etc/mdadm/mdadm.conf /etc/mdadm.conf; do
    if [ -f "$conf" ] && grep -qE "^[[:space:]]*ARRAY[[:space:]]" "$conf" 2>/dev/null; then
      return 0
    fi
  done
  return 1
}

# In auto mode, skip setup if no RAID members/arrays are detected
if [ "$enable_mdraid" = "auto" ] && [ "$force_run" != "yes" ]; then
  if ! is_any_mdraid_detected; then
    touch "$cache_file" 2>/dev/null || true
    exit 0
  fi
fi

if type mdadm &>/dev/null; then
  # Load MDRAID module only if not already loaded
  if [ ! -d /sys/module/md_mod ] && [ ! -e "$proc_mdstat" ]; then
    if modinfo md_mod &>/dev/null; then
      modprobe md_mod 2>/dev/null
      sleep 0.5
    fi
  fi

  echo "Setting up the Software RAID (MDRAID) devices"

  # Scan all physical drives and assemble arrays.
  # The --run flag forces the array to start even if it is degraded.
  # Bounded with timeout to prevent hanging on faulty drives or stalled controllers.
  if type timeout &>/dev/null; then
    timeout "${mdraid_assemble_timeout}" mdadm --assemble --scan --run >/dev/null 2>&1 || true
  else
    mdadm --assemble --scan --run >/dev/null 2>&1 || true
  fi

  # Check if any arrays successfully assembled
  if grep -q "^md" "$proc_mdstat" 2>/dev/null; then
    echo "MDRAID arrays successfully assembled."
  fi

  # Switch any read-only/auto-read-only arrays to read-write mode so they can be mounted or written
  # Skip any array that is registered as a protected source armour device
  if [ -f "$proc_mdstat" ]; then
    for md in $(awk '/^md.*\(.*read-only.*\)/ {print $1}' "$proc_mdstat" 2>/dev/null); do
      if (type is_recorded_source_armour_dev &>/dev/null && is_recorded_source_armour_dev "/dev/$md") || \
         (type is_recorded_source_ro_dev &>/dev/null && is_recorded_source_ro_dev "/dev/$md"); then
        echo "  Keeping protected source MDRAID array /dev/$md in read-only mode."
        continue
      fi
      mdadm --readwrite "/dev/$md" >/dev/null 2>&1 || true
    done
  fi

  # Settle udev events with a bounded timeout (capped at 5 seconds)
  if type udevadm &>/dev/null; then
    udevadm settle --timeout=5 2>/dev/null || udevadm settle 2>/dev/null || true
  fi
fi

touch "$cache_file" 2>/dev/null || true
