#!/bin/bash
#adaptation du srcipt ln_local
#de Philippe Brochard
#
# Modifié le 30/10/03 suprresion prédicat -empty pour cause
# d'incompatibilité avec -depth
# Rajout du paramètre --ignore-fail-on-non-empty de rmdir
# Rajout de l'affichage des Target et Source dans l'usage
TARGET=/opt
SOURCE=${PREFIX:-`pwd`}
VERSION=0.1
BASENAME=`basename $0`
ACTION=""
DIRS="bin doc etc include info lib man sbin share"

usage()
{
   echo "Usage: $BASENAME -action [-t target] [-s source]"
   echo "Action : m create the symlink mirror of source in target (make)"
   echo "         d delete the symlink mirror of source in target (delete)"
   echo "         c search and correct broken symlink in target (clean)"
   echo "         ? print this message"
   echo "         v print version"
   echo "only one action"
   echo "default target : /opt"
   echo "default source \$PREFIX if set or pwd if unset"
   echo "now source = $SOURCE target = $TARGET"
}

ano()
{
  echo "Error you say $BASENAME $ALL"
  usage
  exit 1
}

make()
{
  OLDPWD=`pwd`
  cd ${SOURCE}
  for dir in $DIRS
  do
   if [ -d ${dir} ]
   then
    find ${dir} -type d ! -exec test -d ${TARGET}/\{} \; -exec mkdir ${TARGET}/\{} \;
    find ${dir} \( -type f -o -type l \) -exec ln -sf ${SOURCE}/\{} ${TARGET}/\{} \;
   fi
  done
  cd $OLDPWD
}

clean()
{
   for dir in $DIRS
   do
    echo cleaning ${TARGET}/${dir}
#supprime les liens symbolique dans le vide
    find ${TARGET}/${dir} -type l ! -xtype f -exec rm {} \;
#supprime les sous répertoires vide
     find ${TARGET}/${dir} -depth -mindepth 1 -type d  -exec rmdir --ignore-fail-on-non-empty {} \;
   done
}

delete()
{
  OLDPWD=`pwd`
  cd ${SOURCE}
  for dir in $DIRS
  do
   if [ -d ${dir} ]
   then
     find ${dir} \( -type f -o -type l \) -exec rm ${TARGET}/\{} \;
     find ${TARGET}/${dir} -depth -mindepth 1 -type d  -exec rmdir --ignore-fail-on-non-empty {} \;
   fi
  done
  cd $OLDPWD
}

[ $# = 0 ] && ano
ALL="$@"
while getopts "s:t:cdmv?" PARAM
do
 case $PARAM in
	"?") usage ;exit 0;;
	v)echo $BASENAME ver $VERSION;;
	s)SOURCE=$OPTARG;;
	t)TARGET=$OPTARG;;
	c) [ -n "$ACTION" ] && ano 
	 ACTION=clean;;
	d) [ -n "$ACTION" ] && ano 
	 ACTION=delete;;
	m) [ -n "$ACTION" ] && ano 
	 ACTION=make;;
	*) ano;;
 esac
done
eval ${ACTION:-ano}
echo $ACTION OK
