#!/bin/sh
# Copyright (c) 2006 XenSource Inc.
# Author: Vincent Hanquez <vincent@xensource.com>
#
# storage manager example backend: lvm operations
#

check_arg_ge() {
	if [ "$1" -lt "$2" ]; then exit 3; fi;
}

check_arg_eq() {
	if [ "$1" -ne "$2" ]; then exit 3; fi;
}

sr_create() {
	sruuid=$1
	vgname="VG_XenStorage-${sruuid}"
	shift

	vgcreate ${vgname} $*
	vgs --separator : --noheadings --units k ${vgname} | cut -f 5,6 -d: | \
	         sed -e 's/:/ /'
}

sr_delete() {
	sruuid=$1
	exit 2
}

sr_attach() {
	sruuid=$1
	mkdir -p "/SR-${sruuid}"
	mkdir -p "/SR-${sruuid}/images"
}

sr_detach() {
	sruuid=$1
	rm -rf "/SR-${sruuid}"
}

vdi_create() {
	sruuid=$1
	vdiuuid=$2
	size="$3k"
	vgname="VG_XenStorage-${sruuid}"
	vdiname="LV-${vdiuuid}"
	lvcreate -L${size} -n"${vdiname}" ${vgname}
}

vdi_delete() {
	sruuid=$1
	vdiuuid=$2
	vgname="VG_XenStorage-${sruuid}"
	vdiname="LV-${vdiuuid}"
	lvremove -f "/dev/${vgname}/${vdiname}"
}

vdi_attach() {
	sruuid=$1
	vdiuuid=$2

	ln -f -s "/dev/VG_XenStorage-${sruuid}/LV-${vdiuuid}" \
	         "/SR-${sruuid}/images/${vdiuuid}"
}

vdi_detach() {
	sruuid=$1
	vdiuuid=$2

	rm -f "/SR-${sruuid}/images/${vdiuuid}"
}

vdi_clone() {
	sruuid=$1
	vdiuuid=$2
	dvdiuuid=$3
	vgname="VG_XenStorage-${sruuid}"

	size=$(lvs --separator : --noheadings --units k "${vgname}/LV-${vdiuuid}" \
	      | cut -d: -f 3)
	lvcreate -L${size} -n"LV-${dvdiuuid}" ${vgname}
	if [ $? -ne 0 ]; then exit $?; fi

	dd if="/dev/${vgname}/LV-${vdiuuid}" of="/dev/${vgname}/LV-${dvdiuuid}"
	if [ $? -ne 0 ]; then exit $?; fi
}

vdi_resize() {
	sruuid=$1
	vdiuuid=$2
	newsize=$3
	vgname="VG_XenStorage-${sruuid}"

	lvresize -L${newsize} "${vgname}/LV-${vdiuuid}"
}

cmd=$1
shift
case "$cmd" in
sr_create)
	check_arg_ge $# 2
	sr_create $*
	;;
sr_delete)
	check_arg_eq $# 1
	sr_delete $*
	;;
sr_attach)
	check_arg_eq $# 1
	sr_attach $*
	;;
sr_detach)
	check_arg_eq $# 1
	sr_detach $*
	;;
vdi_create)
	check_arg_eq $# 3
	vdi_create $*
	;;
vdi_delete)
	check_arg_eq $# 2
	vdi_delete $*
	;;
vdi_attach)
	check_arg_eq $# 2
	vdi_attach $*
	;;
vdi_detach)
	check_arg_eq $# 2
	vdi_detach $*
	;;
vdi_clone)
	check_arg_eq $# 3
	vdi_clone $*
	;;
vdi_resize)
	check_arg_eq $# 3
	vdi_resize $*
	;;
*)
	exit 1
esac
exit $?
