#!/bin/sh
set -e
# manage ${PREFIX}/.catkin file
#
# The presence of ${PREFIX}/.catkin is required for some tools.
# This script creates it if needed, and keeps track of which package is using
# it. Since the content of the file does not matter, each package name that
# requires this file is simply added in the file itself when the package is
# added, and removed when the package is deleted.
#

ECHO="echo"
CHMOD="/bin/chmod"
CP="/bin/cp"
FIND="/usr/bin/find"
GREP="/bin/grep"
MKDIR="/bin/mkdir -p"
RM="rm -f"
TEST="test"

CATKIN_MARKER=${PKG_PREFIX}/.catkin
REFDIR=${PKG_REFCOUNT_DBDIR}/${CATKIN_MARKER}
REFCOUNT=${REFDIR}/pkgs

echo=${PKG_VERBOSE:+${ECHO}}
: ${echo:=:}

case $2 in
  POST-INSTALL)
    if ${TEST} -s ${REFCOUNT}; then
      ${echo} "$1: adding reference to catkin marker file"
    else
      ${echo} "$1: creating catkin marker file"
      ${MKDIR} -m 755 ${REFDIR}
    fi
    ${ECHO} "$1" >>${REFCOUNT}
    ${CHMOD} 644 ${REFCOUNT}
    if ${TEST} -e ${CATKIN_MARKER}; then
      if ! ${TEST} -f ${CATKIN_MARKER}; then
        ${ECHO} >&2 "$1: remove ${CATKIN_MARKER}, it's in the way!"
        exit 2
      fi
    else
      >${CATKIN_MARKER}
      ${CHMOD} 644 ${CATKIN_MARKER}
    fi
    ;;

  DEINSTALL)
    if ! ${TEST} -s ${REFCOUNT}; then
      ${echo} "$1: no catkin marker file"
      ${RM} ${CATKIN_MARKER}
      exit 0
    fi

    ${GREP} -v "$1" < ${REFCOUNT} > ${REFCOUNT}.$$ ||:
    ${CP} ${REFCOUNT}.$$ ${REFCOUNT}
    ${RM} ${REFCOUNT}.$$
    ${CHMOD} 644 ${REFCOUNT}
    if ${TEST} -s ${REFCOUNT}; then
      ${echo} "$1: removed from catkin marker file"
    else
      ${echo} "$1: deleting catkin marker file"
      ${RM} ${REFCOUNT}
      ${FIND} ${PKG_REFCOUNT_DBDIR} -type d -empty -delete
      ${RM} ${CATKIN_MARKER}
    fi
    ;;
esac
exit 0
