#!/bin/sh

# Build addon menu files, from the global /Library/GRASS/$GRASS_MMVER/Modules
# and the user's $HOME/Library/GRASS/$GRASS_MMVER/Modules.

# test files to make sure they are appropriate for adding to the GUI menu.
# Using 'file', assume executable binaries OK.  Check scripts to see if they
# have GRASS options configured - a simple grep for #%Module.
# Other script languages may need their own test.

# addon commands can't have spaces in them or sh for loop messes up.
# may be my limited knowledge of sh scripting and there could be a way.

GRASS_MMVER=`cut -d . -f 1-2 "$GISBASE/etc/VERSIONNUMBER"`
BINDIR="$GISBASE_USER/Modules/bin"
SCRIPTDIR="$GISBASE_USER/Modules/scripts"
BINDIRG="$GISBASE_SYSTEM/Modules/bin"
SCRIPTDIRG="$GISBASE_SYSTEM/Modules/scripts"
MENUDIR="$GISBASE_USER/Modules/etc"

echo "Rebuilding Addon menu..."

# just to make sure (startup should have created it)
mkdir -p "$MENUDIR"
echo "# generated by grass startup" > "$MENUDIR/xtnmenu.dat"

# global addons:
if [ -d "$BINDIRG" ] ; then
  cd "$BINDIRG"
  CMDLISTG=`ls -1 2> /dev/null`
else
  CMDLISTG=""
fi
if [ -d "$SCRIPTDIRG" ] ; then
  cd "$SCRIPTDIRG"
  CMDLISTG="$CMDLISTG"$'\n'"`ls -1 2> /dev/null`"
fi
CMDLISTG=`echo "$CMDLISTG" | sort -u`
CMDGFOUND=""

if [ "$CMDLISTG" != "" ] ; then
  for i in $CMDLISTG
  do
    if [ -f "$BINDIRG/$i" ] ; then
      ftype="`file $BINDIRG/$i`"
    else
      ftype="`file $SCRIPTDIRG/$i`"
    fi
    if [ "`echo $ftype | grep 'Mach-O'`" ] || [ "`grep '#% *Module' $BINDIRG/$i 2> /dev/null`" ] || [ "`grep '#% *Module' $SCRIPTDIRG/$i 2> /dev/null`" ] ; then
      echo "main:$i:$i:$i" >> "$MENUDIR/xtnmenu.dat"
      CMDGFOUND="1"
    fi
  done
fi

# user addons:
CMDFIRST="1"
cd "$BINDIR"
CMDLIST=`ls -1 2> /dev/null`
if [ -d "$SCRIPTDIR" ] ; then
  cd "$SCRIPTDIR"
  CMDLIST="$CMDLIST"$'\n'"`ls -1 2> /dev/null`"
fi
CMDLIST=`echo "$CMDLIST" | sort -u`

if [ "$CMDLIST" != "" ] ; then
  for i in $CMDLIST
  do
    if [ -f "$BINDIR/$i" ] ; then
      ftype="`file $BINDIR/$i`"
    else
      ftype="`file $SCRIPTDIR/$i`"
    fi
    if [ "`echo $ftype | grep 'Mach-O'`" ] || [ "`grep '#% *Module' $BINDIR/$i 2> /dev/null`" ] || [ "`grep '#% *Module' $SCRIPTDIR/$i 2> /dev/null`" ] ; then
      if [ "$CMDFIRST" ] && [ "$CMDGFOUND" ] ; then
        echo "separator" >> "$MENUDIR/xtnmenu.dat"
        CMDFIRST=""
      fi
      echo "main:$i:$i:$i" >> "$MENUDIR/xtnmenu.dat"
    fi
  done
fi
