#!/bin/sh
#
# vim:tabstop=3:expandtab:shiftwidth=3 
#
# $Date: 2011-12-22 15:57:09 +0100 (Thu, 22 Dec 2011) $
# $Revision: 390 $
#

if [ "$1" = "" ]
then
   echo
   echo "usage: `basename $0` backupdir"
   echo
   exit 1
fi

LINK_DIR="`echo $1 | sed -e 's,//*,/,g' -e 's,[.]files$,,' -e 's,/$,,'`"

if [ ! -d $LINK_DIR ]
then
   echo
   echo "ERROR; $LINK_DIR is not a directory"
   echo
   exit 1
fi

if [ ! -f $LINK_DIR/.files ]
then
   echo
   echo "ERROR; missing $LINK_DIR/.files"
   echo
   echo "Put all the file names into $LINK_DIR/.files."
   echo "One file per line, with the absolute path."
   echo
   exit 1
fi

egrep -v '^#|^$' $LINK_DIR/.files | while read LINK_FILE
do
   if [ ! -r $LINK_FILE ]
   then
      echo "<!!> $LINK_FILE; Unable to read, skipping..."
   elif [ -d $LINK_FILE ]
   then
      echo "???? $LINK_FILE; Is a directory; cleanup .files, skipping..."
   else
      if [ -f $1/$LINK_FILE ]
      then
         echo " --> $LINK_FILE already linked in"
      else
         unset DIR
         DIR="`dirname $1/$LINK_FILE | sed 's,//*,/,g'`"
         FILE="`basename $1/$LINK_FILE`"
         if [ ! -d $DIR ]
         then
            echo "Creating $DIR"
            mkdir -p $DIR
         fi
         ln $LINK_FILE $DIR/$FILE
         echo "$LINK_FILE -=> $DIR/$FILE"
      fi
   fi
done

