#!/bin/sh

usage () {
   echo "Usage: $0 <project> <package>"
   echo "project: med|junior|desktop|edu|demudi"
   echo "package: package for which the menues should be installed"
}


if [ _"$1"_ == __ ] ; then
   echo "Missing project name."
   usage
   exit -1
fi

if [ _"$2"_ == __ ] ; then
   echo "Missing package name."
   usage
   exit -1
fi

PROJ=$1
case "$PROJ" in
   "med"|"MED")   
            PROJECT="med"
            ;;
   "junior"|"JUNIOR")
            PROJECT="junior"
	    ;;
   "desktop"|"DESKTOP")
            PROJECT="desktop"
	    ;;
   "edu"|"EDU")
            PROJECT="desktop"
	    ;;
   "demudi"|"DEMUDI")
            PROJECT="demudi"
	    ;;
   "lex"|"LEX")
            PROJECT="lex"
	    ;;
   "nonprofit"|"NONPROFIT")
            PROJECT="nonprofit"
	    ;;
   *)
            echo "Wrong project name $PROJ."
            usage
	    exit -1
	    ;;
esac

PKG=$2

if [ `echo "${PKG}" | grep -c "^${PROJ}"` -lt 1 ] ; then
   echo "Warning: Suspicious package name ${PKG}."
   echo "The name should be start with ${PROJ}-."
   usage
fi

if [ ! -d /etc/${PROJ} ] || [ ! -d /etc/${PROJ}/menu ] ; then
   echo "Something went very wrong."
   echo "The subproject ${PROJ} did not install /etc/${PROJ}/menu"
   usage
   exit -1
fi

if [ ! -f /etc/${PROJ}/menu/${PKG} ] ; then
   # ${PROJ}-common does not necessarily have a menu
   if [ "${PKG}" != "${PROJ}-common" ] ; then
      echo "Missing package menu."
      echo "The package ${PKG} does not contain /etc/${PROJ}/menu/${PKG}"
      usage
      exit -1
   else
      # Do nothing if $PKG = ${PROJ}-common and there is no menu
      exit 0
   fi
fi

for user in `get-group-users --simple "${PROJ}"` ; do
   UHOME=`grep -w "${user}" /etc/passwd | sed "s/.*:\([^:]*\):[^:]*$/\1/"`
   if [ ! -d ${UHOME}/.menu ] ; then
      mkdir -p ${UHOME}/.menu
      chown ${user}: ${UHOME}/.menu
   fi
   cp -a /etc/${PROJ}/menu/${PKG} ${UHOME}/.menu
   chown ${user}: ${UHOME}/.menu/${PKG}
   su ${user} -c update-menus
done
