#!/bin/bash
# -*- coding: utf-8 mode: sh -*- vim:sw=4:sts=4:et:ai:si:sta:fenc=utf-8

BCKDIR="${1:-/backup}"
VGNAME="$2"
LVNAME="$3"

###############################################################################
# Ne pas modifier à partir d'ici

function die() {
    [ -n "$*" ] && echo "$*"
    exit 1
}

mountvg=
mount=
mountrw=

# Vérifier que le volume group est monté
if [ -n "$VGNAME" ]; then
    # Vérifier la présence du volume group
    found=
    try=1
    while [ "$try" -le 2 ]; do
        VGNAMES=($(vgs --noheadings -o vg_name | sed 's/ //g'))
        for vgname in "${VGNAMES[@]}"; do
            if [ "$vgname" == "$VGNAME" ]; then
                found=1
                break
            fi
        done
        if [ -n "$found" ]; then
            break
        else
            vgscan >&/dev/null
            try=$(($try + 1))
        fi
    done
    [ -n "$found" ] || die "ERR volume group $VGNAME not found"

    # Vérifier qu'il est monté
    if [ ! -d "/dev/$VGNAME" ]; then
        vgchange -ay "$VGNAME" >&/dev/null
        mountvg=1
    fi
    [ -d "/dev/$VGNAME" ] || die "ERR directory /dev/$VGNAME not found"
fi

# Vérifier que le répertoire est monté
if [ ! -d "$BCKDIR" ]; then
    mkdir "$BCKDIR" >&/dev/null || die "ERR cannot mkdir $BCKDIR"
fi
if ! mount | grep -q "on $BCKDIR "; then
    if grep -q "$BCKDIR" /etc/fstab; then
        mount "$BCKDIR" >&/dev/null || die "ERR cannot mount $BCKDIR"
        mount=1
    elif [ -n "$LVNAME" -a -n "$VGNAME" ]; then
        mount "/dev/$VGNAME/$LVNAME" "$BCKDIR"
        mount=1
    fi
fi

# Vérifier que le répertoire est monté en lecture/écriture
if ! mount | grep "on $BCKDIR " | grep -q '(.*rw.*)'; then
    mount -o remount,rw "$BCKDIR" >&/dev/null || die "ERR cannot remount $BCKDIR as R/W"
    mountrw=1
fi

echo OK "$BCKDIR" "$VGNAME" "$LVNAME" ${mountvg:+ mounted_vg}${mount:+ mounted}${mountrw:+ mounted_rw}
