#!/bin/sh

function usage() {
	echo "Usage:"
	echo "  ${0##*/} <host> <lv-path> [vgname] [pvname]"
	exit 1
}

HOST="$1"
if [ -z "$HOST" ]; then
        usage
fi

LV="$2"
if [ -z "$LV" ]; then
        usage
fi

VGNAME="$3"
PV="$4"

LE=$(lvdisplay "$LV" | awk '/Current LE/ {print $3}')
[ -z "$VGNAME" ] &&	VGNAME=$(lvdisplay "$LV" | awk '/VG Name/ {print $3}')
LVNAME=$(lvdisplay "$LV" | awk '/LV Name/ {print $3}')
[ "$?" != "0" ] && exit 1

ssh $HOST ":"
[ "$?" != "0" ] && exit 1

VGD=$(ssh $HOST vgdisplay $VGNAME 2>/dev/null| grep "VG Name" | awk '{print $3}')
if [[ "$VGD" = "" ]]; then
	echo "Error! Destination VG $VGNNAME not exists!"
	exit 1
fi

LED=$(ssh $HOST lvdisplay $LV 2>/dev/null| grep "Current LE" | awk '{print $3}')
if [[ "$LED" != "" ]]; then
	if [[ "$LE" = "$LED" ]]; then
		echo "Destination LV already exists."
		exit 0
	else
		echo "Error! Destination LV already exists, with another size."
		exit 1
	fi
fi
ssh $HOST lvcreate -n "$LVNAME" -l "$LE" "$VGNAME" "$PV"
