#!/bin/sh
#
# Author: Petter Reinholdtsen <pere@hungry.com>
# Date:   2002-04-28
#
# Initialise LVM partitions.  This script should only be used the
# first time LVM partitions are created.
#
#  - adds all LVM partitions to one volume group localhost_vg
#  - creates new logical volume home_lv
#  - creates file system on new logical volume
#
# Usage: lvm-initialize-debian-edu [vg-name [lv-name [lv-size]]]

set -ex

disks=`cat /proc/partitions|egrep 'ide|scsi'|awk '{print $4}'|grep '/disc'|sed 's%^%/dev/%'`

# Make sure the disks exists in /dev/.  If not, the kernel is probably
# compiled with devfs support, but /dev/ is not devfs.  Such
# configuration will not work.  A workaround for this is to install
# devfsd and edit /etc/default/devfsd to mount devfs on /dev/ at boot
# time.
for disk in $disks ; do
    if test ! -e $disk ; then
	echo "error: unable to find $disk mentioned in /proc/partitions"
	echo "error: $0 will not work in this configuration."
	exit 1
    fi
done

lvmpartitions=`fdisk -l $disks 2>/dev/null|grep 'Linux LVM$' | awk '{print $1}'`

if [ "isneeded" = "$1" ] ; then
    if [ -z "$lvmpartitions" ] ; then
	# No LVM partitions found, initialisation isn't needed
	exit 1
    fi
    exit 0
fi

if test -z "$lvmpartitions" ; then
    echo "No Linux LVM partitions on any of the known disks."
    exit 1
fi

# Make sure LVM isn't active when overwriting the LVM partitions
/etc/init.d/lvm stop || true

# Zero out old LVM headers, making sure pvcreate do not protest
# This will wipe out all previous LVM volumes
#This is now done by autopartkit.  No need to do it here, and it make this
#script less destructive for existing LVM volumes.
#for dev in $lvmpartitions ; do
#    dd bs=100k count=1 if=/dev/zero of=$dev
#done

# Then, try to install the LVM service This only works with 2.4.x kernel
/etc/init.d/lvm restart || true

if [ ! -d /proc/lvm ] ; then
    echo "No LVM support in the kernel.  Unable to initialise LVM!"
    exit 1
fi

if [ ! -z "$1" ] ; then
    vgname="$1"
else
    vgname=localhost_vg
fi
if [ ! -z "$2" ] ; then
    lvname="$2"
else
    lvname=home_lv
fi
if [ ! -z "$3" ] ; then
    lvsize="$3"
else
    lvsize=500 # MB - start small, it can be resized. :-)
fi

echo "Creating LVM physical volume on $lvmpartitions"
pvcreate $lvmpartitions

echo "Creating LVM volume group '$vgname' from $lvmpartitions"
vgcreate $vgname $lvmpartitions

echo "Create LVM $lvsize MB logical volume '$lvname' on '$vgname'."
lvcreate -L$lvsize -n$lvname $vgname

echo "Make ext3 file system on the logical volume $lvname."
mke2fs -j /dev/$vgname/$lvname

vgdisplay

exit 0
