#!/bin/sh
# 
# Author:	Finn-Arne Johansen <faj@bzz.no>
# License:      GPL-2, on debian, look in /usr/share/common-licenses/GPL-2
#
# Add to startup with command
#  update-rc.d resize_lvm start S 32 .
#
### BEGIN INIT INFO
# Provides:          resize_lvm
# Required-Start:    checkroot
# Should-Start:      lvm
# Required-Stop:     
# Default-Start:     S
# Default-Stop:      
# Short-Description: Init script to resize lvm volumes during bootup
# Description:       Resizing(extending) lvm logical volumes during startup.
#                    To use it, create/edit /etc/default/resize_lvm
#                    and set the new size of volumes there.  The
#                    format is lvm device path and new size in MiB
#                    separated by colon and a trailing colon.  The
#                    size need to be an integer.
#                    Example:
#                      /dev/vg_data/lv_backup:60:
#                    This will change the size of lv_backup to 60 MiB.
### END INIT INFO

set -e 

resize_lvm() {
    cfg=/etc/default/resize_lvm
    if [ -f $cfg ] ; then 
	echo "info: Extending LVM volumes requested, $cfg present"
	export LC_ALL=C
	grep -vE "^#|^$" /etc/default/resize_lvm | while read LINES ; do 
	    DEVNAME=$(echo "$LINES" | /bin/sed -ne "s#^\([/a-z0-9_-]*\):.*#\1#p")
	    NEWSIZE=$(echo "$LINES" | \
		/bin/sed -ne "s#^[/a-z0-9_-]*:\([0-9]*\):.*#\1#p")
	    CURSIZE=$(/sbin/lvdisplay --units m $DEVNAME | \
		/bin/sed -ne 's:.*LV Size *\([0-9]*\)\.[0-9]* MB$:\1:p')
	    if [ "$NEWSIZE" -lt "$CURSIZE" ] ; then
		echo "warning:   Unsupported request to shrink $DEVNAME."
	    elif [ "$NEWSIZE" -gt "$CURSIZE" ] ; then
		echo "info:   Extending $DEVNAME from $CURSIZE to $NEWSIZE MiB"
                # lvextend exist for both lvm 1 and 2, while lvresize
                # only exist for lvm 2.  Using lvextend because of
                # this. [pere 2006-03-26]
		(
		    /sbin/e2fsck -fy "$DEVNAME" && \
			/sbin/lvextend -L ${NEWSIZE}M "$DEVNAME" && \
			/sbin/resize2fs "$DEVNAME" || /bin/true
		) 2>&1 | sed 's/^/  /g'
	    fi
	done
    fi
}

case $1 in 
    start)
	resize_lvm
	;;
    stop|reload|restart|force-reload)
	exit 0 # Nothing to do
	;;
    *)
	echo "error: Sorry, this script is only usable during startup" 
	exit 1
	;;
esac

exit 0
