#!/bin/sh
#
# Copyright © 2006 Martin F. Krafft <madduck@debian.org>
# based on the scripts in the initramfs-tools package.
# released under the terms of the Artistic Licence.
#
# $Id: script.local-top 290 2006-12-19 08:18:50Z madduck $
#

set -eu

PREREQ="udev_helper"

prereqs()
{
	echo "$PREREQ"
}

case ${1:-} in
  prereqs)
    prereqs
    exit 0
    ;;
esac

. /scripts/functions

if [ -e /scripts/local-top/md ]; then
  log_warning_msg "old md initialisation script found, getting out of its way..."
  exit 1
fi

MDADM=/sbin/mdadm
[ -x "$MDADM" ] || exit 0

verbose()
{
  case "$quiet" in y*|Y*|1|t*|T*)
    return 1;;
  *)
    return 0;;
  esac
}

MD_DEVS=all
MD_MODULES='linear multipath raid0 raid1 raid456 raid5 raid6 raid10'
[ -s /conf/md.conf ] && . /conf/md.conf

verbose && log_begin_msg Loading MD modules
for module in ${MD_MODULES:-}; do
  if modprobe --syslog "$module"; then
    verbose && log_success_msg "loaded module ${module}."
  else
    log_failure_msg "failed to load module ${module}."
  fi
done
log_end_msg

if [ ! -f /proc/mdstat ]; then
  verbose && panic "cannot initialise MD subsystem (/proc/mdstat missing)"
  exit 1
fi

# handle /dev/md/X nodes
mkdir --parent /dev/md

CONFIG=/etc/mdadm/mdadm.conf
# in case the hook failed to install a configuration file, this is our last
# attempt... the "emergency procedure"... <drumroll>
if [ ! -e $CONFIG ]; then
  log_warning_msg "missing mdadm.conf file, trying to create one..."
  mkdir -p ${CONFIG%/*}
  echo DEVICE partitions > $CONFIG
  $MDADM --examine --scan >> $CONFIG
  if [ -s $CONFIG ]; then
    verbose && log_success_msg "mdadm.conf created."
  else
    verbose && log_failure_msg "could not create mdadm.conf, the boot will likely fail."
  fi
  MD_DEVS=all
fi

if [ "$MD_DEVS" = all ]; then
  
  verbose && log_begin_msg "Assembling all MD arrays"
  extra_args=''
  [ -n "$MD_HOMEHOST" ] && \
    extra_args="--homehost='$MD_HOMEHOST' --auto-update-homehost"
  if $MDADM --assemble --scan --run --auto=yes $extra_args; then
    verbose && log_success_msg "assembled all arrays."
  else
    log_failure_msg "failed to assemble all arrays."
  fi
  verbose && log_end_msg

elif [ "$MD_DEVS" != none ]; then
  for dev in $MD_DEVS; do

    verbose && log_begin_msg "Assembling MD array $dev"
    if $MDADM --assemble --run --auto=yes $dev; then
      verbose && log_success_msg "started $dev"
    else
      log_failure_msg "failed to start $dev"
    fi
    verbose && log_end_msg

  done
fi

exit 0
