#!/bin/bash
#
# $Id$
#
# Copyright ITEG IT-Engineers GmbH 2016
#
# default script to configure as lxc.hook.pre-mount
#
# uses LXC_NAME to read matching /etc/lxcutils/conf/${LXC_NAME}.conf
# and calls lcu-mount to make sure everything is mounted, which can include
#   drbd primary CTDRBDRES
#   mount /var/lib/lxc/$CTLVNAME

if [ -z "${LXC_NAME}" ] ; then
  echo "ERROR: \$LXC_NAME empty"
  exit 1
fi

CTNAME=$LXC_NAME

# LXC logs the hook scripts' output somewhere, but we want to 
# 1. make it easy to find in background mode
# 2. get direct output when run in foreground mode, including pure hook script tests
# Therefore we use tee and 2>&1 to get relevant output in the logfile as well as stdout
LOGFILE=$(cat /var/lib/lxc/${CTNAME}/config |egrep "^lxc.logfile" |cut -f2 -d'=' |tr -d ' ')
if [ -z "$LOGFILE" ] ; then 
  LOGFILE="/var/log/lxc/${CTNAME}.log"
fi

DATE=$(date)
echo "Default pre-start hook $0 called at $DATE" |tee -a ${LOGFILE}

if [ ! -f /etc/lxcutils/conf/${CTNAME}.conf ] ; then
  echo "ERROR: Config file missing: /etc/lxcutils/conf/${CTNAME}.conf" |tee -a ${LOGFILE}
  exit 2
fi

echo "Calling lcu-mount ${CTNAME}" |tee -a ${LOGFILE}
lcu-mount $CTNAME 2>&1 |tee -a ${LOGFILE}
PRC=${PIPESTATUS[0]}
if [ "$PRC" != "0" ] ; then 
  echo "ERROR: Failed to lcu-mount ${CTNAME}, lcu-mount returned $PRC" |tee -a ${LOGFILE}
  exit 11 
fi

echo "Calling lcu-nat ${CTNAME}" |tee -a ${LOGFILE}
lcu-nat $CTNAME 2>&1 |tee -a ${LOGFILE}
PRC=${PIPESTATUS[0]}
if [ "$PRC" != "0" ] ; then 
  echo "ERROR: Failed to lcu-mount ${CTNAME}, lcu-nat returned $PRC" |tee -a ${LOGFILE}
  exit 12
fi

DATE=$(date)
echo "$0 done for good at $DATE" |tee -a ${LOGFILE}

exit 0

