#!/bin/sh

if [ -z $LD_LIBRARY_PATH ]; then
	LP=$(ldd /usr/bin/sh | grep " => " | head -1 | sed -e "s/.*=> *//" -e "s/ *(.*//" -e "s:/[^/]*$::")
	LP=${LP#/usr}

	export LD_LIBRARY_PATH=${SNAP}${LP}:${SNAP}/usr${LP}${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}
	logger Set LD_LIBRARY_PATH to $LD_LIBRARY_PATH
fi

MAJ_VER=$(uname -r | cut -d'.' -f1)
MIN_VER=$(uname -r | cut -d'.' -f2)
RUNNING_KERNEL_VER=$(printf "%d%2.2d\n" $MAJ_VER $MIN_VER)
if [ ${RUNNING_KERNEL_VER} -ge 519 ]; then
  BINARY="keepalived-519"
elif [ ${RUNNING_KERNEL_VER} -ge 515 ]; then
  BINARY="keepalived-515"
elif [ ${RUNNING_KERNEL_VER} -ge 508 ]; then
  BINARY="keepalived-508"
elif [ ${RUNNING_KERNEL_VER} -ge 504 ]; then
  BINARY="keepalived-504"
elif [ ${RUNNING_KERNEL_VER} -ge 418 ]; then
  BINARY="keepalived-418"
elif [ ${RUNNING_KERNEL_VER} -ge 415 ]; then
  BINARY="keepalived-415"
elif [ ${RUNNING_KERNEL_VER} -ge 305 ]; then
  BINARY="keepalived-313"
else
  echo "ERROR! You are running kernel ${RUNNING_KERNEL_VER},"
  echo "       which is not currently supported by the keepalived snap."
  echo "If you need support for kernel ${RUNNING_KERNEL_VER} please file"
  echo "an issue: https://github.com/acassen/keepalived/issues"
exit 1
fi

# The magic file must be the one in the snap
MAGIC="${SNAP}/usr/share/misc/magic"
export MAGIC

exec "${SNAP}/usr/sbin/${BINARY}" "$@"
