#!/bin/sh
#
# 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
# stop lvm's if any
if find /sys/class/block/$disk_name*/holders/ -mindepth 1 | grep -q holders/dm; then
   if command -v vgchange >/dev/null; then
      vgchange -a n
   else
      echo "WARNING: vgchange command not found" >&2
   fi
fi

# stop mdadm raids if any
if [ -r /proc/mdstat ]; then
   md_name="\$(awk "/$disk_name/ {print \$1}" /proc/mdstat)"
   if [ -n "\$md_name" ]; then
      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
   fi
fi

if command -v pvremove >/dev/null; then
   pvremove --force --force --yes "$disk" || true
else
   echo "WARNING: pvremove command not found" >&2
fi
if command -v mdadm >/dev/null; then
   mdadm --zero-superblock --force "$disk" || true
else
   echo "WARNING: mdadm command not found" >&2
fi
# 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
