#!/bin/bash
#
# $Id: lcu-hook-pre-start 60 2019-04-24 18:26:36Z lxcutils $
#
# Copyright ITEG IT-Engineers GmbH 2021
#
# Adapts the /etc/lxcutils/conf/${CTNAME}.lxc file by piping it through
#   sed -z -f /usr/share/lxcutils/veth2ipvlan-z.sed
# if
#   systemd-detect-virt
# says 'vmware', or through
#   sed -z -f /usr/share/lxcutils/ipvlan2veth-z.sed 
# otherwise.
#
# The actual .lxc file is only replaced if the sed operation results in changes.

CTNAME="$1"
shift

if [ -z "${CTNAME}" ] ; then
  echo "ERROR: No container name specifed as \$1."
  exit 1
fi

if [ ! -f /etc/lxcutils/conf/${CTNAME}.lxc ] ; then
  echo "ERROR: No .lxc file /etc/lxcutils/conf/${CTNAME}.lxc"
  exit 2
fi

SDV=$(systemd-detect-virt 2>/dev/null)

if [ -z "${SDV}" ] ; then
  echo "ERROR: systemd-detect-virt did not give us any information."
  echo "Not touching /etc/lxcutils/conf/${CTNAME}.lxc"
  exit 11
fi

echo "Debug: SDV=${SDV}"

if [ "${SDV}" == "vmware" ] ; then
  echo "Detected VMWare virt environment, checking if ${CTNAME}.lxc needs switch from veth to ipvlan"
  sed -z -f /usr/share/lxcutils/veth2ipvlan-z.sed \
    /etc/lxcutils/conf/${CTNAME}.lxc >/etc/lxcutils/conf/${CTNAME}.lxc.ipvlan
  cmp -s /etc/lxcutils/conf/${CTNAME}.lxc /etc/lxcutils/conf/${CTNAME}.lxc.ipvlan
  if [ "$?" != "0" ] ; then
    echo "Replacing /etc/lxcutils/conf/${CTNAME}.lxc with ipvlan variant"
    cp -av /etc/lxcutils/conf/${CTNAME}.lxc        /etc/lxcutils/conf/${CTNAME}.lxc.bak || exit 21
    cp -av /etc/lxcutils/conf/${CTNAME}.lxc.ipvlan /etc/lxcutils/conf/${CTNAME}.lxc     || exit 22
  else
    echo "No need to adapt /etc/lxcutils/conf/${CTNAME}.lxc"
    #rm -v /etc/lxcutils/conf/${CTNAME}.lxc.ipvlan || exit 29
  fi
else
  echo "Detected Non-VMWare virt environment '${SDV}', checking if ${CTNAME}.lxc needs switch from ipvlan to veth"
  sed -z -f /usr/share/lxcutils/ipvlan2veth-z.sed \
    /etc/lxcutils/conf/${CTNAME}.lxc >/etc/lxcutils/conf/${CTNAME}.lxc.veth
  cmp -s /etc/lxcutils/conf/${CTNAME}.lxc /etc/lxcutils/conf/${CTNAME}.lxc.veth
  if [ "$?" != "0" ] ; then
    echo "Replacing /etc/lxcutils/conf/${CTNAME}.lxc with veth variant"
    cp -av /etc/lxcutils/conf/${CTNAME}.lxc      /etc/lxcutils/conf/${CTNAME}.lxc.bak || exit 31
    cp -av /etc/lxcutils/conf/${CTNAME}.lxc.veth /etc/lxcutils/conf/${CTNAME}.lxc     || exit 32
  else
    echo "No need to adapt /etc/lxcutils/conf/${CTNAME}.lxc"
    #rm -v /etc/lxcutils/conf/${CTNAME}.lxc.veth || exit 39
  fi
fi

echo ""
echo "ls-ing /etc/lxcutils/conf/${CTNAME}.lxc*"
ls -ld /etc/lxcutils/conf/${CTNAME}.lxc*
echo ""

exit 0


