#!/bin/ksh

dslsSource=$STARTDIR
dslsTarget=$1
unitdir="$(/usr/bin/pkg-config systemd --variable=systemdsystemunitdir)"
function updateConfigEnv 
{
  if [[ -n ${DSLAWSID} ]] 
    then
      sed -i 's/Environment=/Environment=\"DSLAWSID=TRUE\"/' "${unitdir}/dsls.service"
    else
      sed -i '/Environment=/d' "${unitdir}/dsls.service"
  fi
}

if [ -z "${unitdir}" -o ! -d "${unitdir}" ] ; then
  echo "Error, unable to find unit directory for systemd, aborting."
  exit 1
else
  echo "Checking dsls config in directory (${unitdir})..."
  if [ ! -f "${unitdir}/dsls.service" ] ; then
    echo "Adding new dsls config in directory (${unitdir})..."
    sed "s:PATH_TO_CUSTOMIZE:$dslsTarget:g" "${STARTDIR}/dsls.service" | sed "s:START_ARGS_TO_CUSTOMIZE:$START_ARGS:g" > "${unitdir}/dsls.service"
    updateConfigEnv
    /usr/bin/systemctl enable dsls.service
    rc=$?
  else
    echo "dsls config found in directory (${unitdir}), replacing old dsls config file..."
    chmod +w "${unitdir}/dsls.service"
    sed "s:PATH_TO_CUSTOMIZE:$dslsTarget:g" "${STARTDIR}/dsls.service" | sed "s:START_ARGS_TO_CUSTOMIZE:$START_ARGS:g" > "${unitdir}/dsls.service"
    updateConfigEnv
    /usr/bin/systemctl daemon-reload
    rc=$?
  fi
fi

exit $rc
