#!/bin/sh -e
#
# 2012 Steven Armstrong (steven-cdist at armstrong.cc)
#
# This file is part of cdist.
#
# cdist is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# cdist is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with cdist. If not, see <http://www.gnu.org/licenses/>.
#

disk="/$__object_id"
disk_name="${disk##*/}"

cat << DONE

debug() {
   echo "[DEBUG] \$@" >&2
}

find_md_device_names() {
   local disk_name="\$1"
   for slave in \$(find /sys/devices/virtual/block/*/slaves/ -name "\${disk_name}*"); do
      debug "slave: \$slave"
      for holder in \$slave/holders/*; do
         debug "holder: \$holder"
         if [ -d "\$holder/md" ]; then
            debug "mdadm found at \$holder"
            holder_name="\${holder##*/}"
            echo "\$holder_name"
         fi
      done
   done
}

# disable any enabled volume group
if command -v vgchange >/dev/null; then
   vgchange -a n
else
   echo "WARNING: vgchange command not found" >&2
fi

# disable any running mdadm arrays related to $disk
for md_name in \$(find_md_device_names "$disk_name" | sort | uniq); do
   echo "md_name: \$md_name"
   if command -v mdadm >/dev/null; then
      mdadm --stop "/dev/\$md_name"
   else
      echo "WARNING: mdadm command not found" >&2
      echo "WARNING: could not stop active mdadm raid for disk $disk" >&2
   fi
done

# clean disks from any legacy signatures
if command -v wipefs >/dev/null; then
   wipefs -a "$disk" || true
fi

# erase partition table
dd if=/dev/zero of=$disk bs=512 count=1
printf 'w\n' | fdisk -u -c $disk || true
DONE
