#! /bin/sh
# Smalltalk package installer

: ${prefix:=/usr}
: ${exec_prefix:=/usr}
: ${AWK:=awk}
: ${GST:=/usr/bin/gst}
IMAGE_PATH=${SMALLTALK_IMAGE:-/usr/share/gnu-smalltalk}
KERNEL_PATH=${SMALLTALK_KERNEL:-/usr/share/gnu-smalltalk/kernel}
MODULE_PATH=${SMALLTALK_MODULES:-/usr/lib/gnu-smalltalk}

request_help=false
request_version=false
load=true
install=true
dry_run=false
files=

while [ -n "$1" ]; do
  case $1 in
  	--version)	 request_version=true	;;
  	--help)		 request_help=true	;;
  	--no-load)	 load=false		;;
  	--no-install)	 install=false		;;
  	-n|--dry-run)	 dry_run=true		;;
  	*)		 files="$files $1"	;;
  esac
  shift
done

if $request_version; then
  echo GNU Smalltalk package installer, version 1.95.10
  exit 0
fi

if [ -z "$files" ] || $request_help; then
  cat <<EOF
Syntax: gst-package [OPTION]... FILE...

    -n, --dry-run         print commands rather than running them
	--help            display this message and exit
	--no-load         don\'t load the Smalltalk files in the image
        --no-install      don\'t copy the external modules to the module path
	--version         print version information and exit

gst-package requires write access to the \`packages\' file in the GNU
Smalltalk image directory, and installs the packages whose description
is contained contained in the given files.  The format of the files is:

    package-name
       prerequisites
       files-to-load
       start-dir (relative to the kernel path)

Files-to-load can contain Smalltalk files (with a .st extension) or
modules.  Smalltalk files have paths relative to the start-dir,
while module files are dynamically loaded and they are searched
in the file system just like every other shared library, but also
in $MODULE_PATH.

The image path is $IMAGE_PATH.
The kernel path is $KERNEL_PATH.

EOF
  # If no options were passed, return an error.
  $request_help && exit 0
  exit 1
fi

echo "cat $files >> $IMAGE_PATH/packages"
$dry_run || cat $files >> $IMAGE_PATH/packages

if $install; then
  for file in $files; do
    modules="$modules `$AWK '
	BEGIN { FS="#"; n = 3 }
	length ($1) > 0 {
	  n++;
	  if (n == 4) { name = $1; n = 0; }
	  if (n == 2) { printf "%s ", $1; }
	}' $file`"
  done

  modules="`echo $modules|sed 's/[^ ]*\.st//g; s/  */ /g; s/ *$/ /;
            s/^ *//; s/ /* /g'`"

  if [ -n "$modules" ]; then
    echo cp -p $modules $MODULE_PATH
    $dry_run || cp -p $modules $MODULE_PATH
  fi
fi

if $load; then
  for file in $files; do
    pkgs="$pkgs `$AWK '
	BEGIN { FS="#"; n = 3 }
	length ($1) > 0 {
	  n++;
	  if (n == 4) { name = $1; n = 0; }
	  if (n == 3) { printf "%s ", name; }
	}' $file`"
  done

  if [ -n "$pkgs" ]; then
    echo $GST -qK Load.st -a $pkgs
    $dry_run || $GST -qK Load.st -a $pkgs
  fi
fi
