#!/bin/sh
#
# This code is covered by the GNU General Public License (GPLv2 or higher)
# Copyright (C) 2010  Andrew V. Stepanov <stanv@altlinux.org>
#
# This postscript attended to be executed at Compute KVM Host Nodes.
#
# Make /etc/fstab entry for mount shared filesystem between Managment node and Host nodes to
# share virtual machines disks.
#
# Mount point and exported NFS share must have same path on Managment and Compute nodes.
#

# Script name
PROG="${PROG:-${0##*/}}"

# Messager for outer world
log() {
    local msg="$@"
    if [ -z "$(echo $msg | sed -e 's/[[:space:]]//g')" ]; then
        return
    fi
    logger -t xcat "$PROG: $msg"
}

# Check that script called under right circumstances
if [ -z "$MASTER" -o -z "$INSTALLDIR" ]; then
    log "Incorrect postscript invocation"
    exit 0
fi

# General definitions
VMSDIR="$INSTALLDIR/vms"
SERVER="${NFSSERVER:-$MASTER}"

# Create mount point
log "Create mount point $VMSDIR"
if ! mkdir -p "$VMSDIR"; then
    log "Something wrong: can't create $VMSDIR"
    exit 0
fi

# Don't do anything if this script was previous executed.
if grep -qsE "^[^#]*$VMSDIR.*$" "/etc/fstab"; then
    log "Found $VMSDIR at /etc/fstab - nothing to do."
    exit 0
fi

# Test /etc/fstab for writable
if ! [ -w "/etc/fstab" ]; then
    log "Can't write to /etc/fstab"
    exit 0
fi

# Update /etc/fstab
log "Update /etc/fstab: auto mount $VMSDIR from $SERVER:$VMSDIR"
echo "$SERVER:$VMSDIR $VMSDIR nfs rsize=8192,wsize=8192,timeo=14,intr,nfsvers=2 1 2" >> "/etc/fstab"

# Mount NFS share
log "Mount $VMSDIR"

if mount "$VMSDIR" >/dev/null 2>&1; then
    log "$VMSDIR successfuly mounted"
else
    log "Can't mount $VMSDIR, check server ($SERVER) configuration"
fi
