#!/bin/bash
#
# /opt makeup script
#
# (c) 2001 Peter Baudis <pasky@pasky.ji.cz>
#
# This script is written to be used as indexer of /opt directory. It can
# search all the /opt directory for binary files, manual pages, etc, and
# put them all to PATH env variables or symlink them to some big directories.
#
# /opt directory is done from lotsa other dirs, each named by program it
# contains, and in there are classical /bin, /sbin, /etc or /lib dirs...
#
# Note that if .nodir is found in any package's directory (either root or
# interesting (one of $DIRS, but NOT mapped, these aren't)), this directory
# will not be indexed. If there's /.mapdir, you can place there your own
# directory-to-public mapping, in format type:dir_name, where type is one
# from DIRS - one line means one mapping.
#

DIRS="bin sbin man/* lib libexec etc include info share/aclocal share/aclocal-"

#
# Define a function for easy linking directory into base
#

function linkdir () {
  glob="`pwd`/$2/*"
  dest="/opt/base/$1"
  domkdir=1
  
  # Switch special cases
  case $1 in
    # XXX
    share/aclocal-) if [ ! -d /opt/base/share ]; then mkdir /opt/base/share /opt/base/share/aclocal; fi; dest="/opt/base/share/aclocal" ;;
    share/aclocal) if [ ! -d /opt/base/share ]; then mkdir /opt/base/share /opt/base/share/aclocal; fi ;;

    lib) glob="`pwd`/$2/*.so* `pwd`/$2/*.a";;
    etc) glob="`pwd`/$2"; dest="/opt/base/$1/$3"; mkdir -m 755 -p /opt/base/$1; domkdir="";;
    info) rm -f `pwd`/$2/dir;;
  esac

  glob=`ls -d $glob 2>/dev/null`
 
  if [ "$dest" ] && [ ! -d $dest ] && [ $domkdir ]; then
    mkdir -m 755 -p $dest || ( echo "Cannot mkdir $dest!" >&2 && exit 1 )
  fi
 
  [ "$glob" ] && [ "$dest" ] && ln -s $glob $dest
}

#
# And walk thru tree
#

cd /opt

for pkg in *; do

  # Don't check special dirs
  
  if [ "$pkg" == "lost+found" ] || [ "$pkg" == "base" ]; then
    continue
  fi
  
  # It's a directory
  
  if [ -d "$pkg" ]; then

    # It's permitted to include
    
    if [ ! -e "$pkg/.nopath" ]; then
    
      cd $pkg
      
      # Walk into known subdirs
      
      for dir in $DIRS; do
	if [ -d $dir ]; then
	  if [ ! -e $dir/.nopath ]; then
	    linkdir $dir $dir $pkg
	  fi
	fi
      done

      # Check user-defined mapping
      
      if [ -d $pkg/.mapdir ]; then
        {
	  read mapline
	  if [ "`echo $mapline | grep :`" ]; then
	    linkdir `echo $mapline | cut -d : -f 1` `echo $mapline | cut -d : -f 2` $pkg
	  fi
	} < ${pkg}/.mapdir
      fi

      cd /opt
      
    fi
    
  fi
  
done
