#!/bin/sh

# install_module <from> <to>

if [ "$1" = "--help" ] ; then
cat <<EOF
  Installs a module (.pmod file or directory, or a .so file)
  in a destination directory. Called by "make install".

  Usage:

    install_module source destination_directory
EOF
exit 0
fi


FROM="$1"
TO="$2"

DIRS_TO_MAKE=

DIR="$TO"
while :
do
  DIR=`echo $DIR | sed -e 's@/[^/]*$@@' -e 's@/$@@'`

  case "$DIR" in
    *.pmod)
      if [ -d "$DIR" ]; then
         break
      fi

      if [ -f "$DIR" ]; then
        mv "$DIR" "$DIR-foo"
        mkdir $DIR
        mv "$DIR-foo" "$DIR/module.pmod"
        break
      fi

      BASE=`echo $DIR | sed -e 's/\.[^.]*$//'`

      if [ -f "$BASE.so" ]; then
        mkdir "$DIR"
        mv "$BASE.so" "$DIR/module.so"
        break
      fi

#FIXME: Add sed expression to quote spaces, quotes etc. in $DIR
      DIRS_TO_MAKE="$DIR $DIRS_TO_MAKE"
    ;;
    *) break ;;
  esac

done

BASE=`echo $TO | sed -e 's/\.[^.]*$//'`

if test "x$DIRS_TO_MAKE" != x; then
  mkdir $DIRS_TO_MAKE
else
  :
fi

if [ -d "$BASE.pmod" -a -d "$FROM" ]; then
# we are copying a dir module into a dir module.
  FROM="$FROM/."
elif [ -d "$BASE.pmod" ]; then
  EXT=`echo $TO | sed -e 's@^.*\.\(.[^\.]*\)$@\1@'`
	  TO="$BASE.pmod/module.$EXT"
fi

# Add proper flag to copy recursively if FROM is a directory module

CPFLAGS=""

if [ -d "$FROM" ]; then
  CPFLAGS="-r"
fi

cp $CPFLAGS "$FROM" "$TO"

exit $?
