#!/bin/bash

# This script reconstructs parts of a directory tree with symbolic links.
# I use it in order to publish automatically selected parts of my 
# hard disk on a web server. Only files and directories within folders
# named PUBLIC are published. Your webserver needs to be configured 
# to allow browsing of directories since no table of contents is 
# generated.

# The script searches for directories named PUBLIC under $SOURCEROOT.
# Every directory found will be sybolically linked under the $DESTROOT
# directory. At this the directory PUBLIC itself will be omitted so that
# the published does not contain any PUBLIC directory.   

# version 2.0 
# date 8.9.2011

# new in version 2.0: use nested find commands instead of 
# shell expansion, see below

SOURCEROOT="/home/jens/Documents/Schule/config-Students_pub_docs" 


DESTROOT="/tmp/Public-Documents"


cd "$SOURCEROOT"

#echo -e \\n \\n List of cleaned directories
rm -r "$DESTROOT"
#find "$DESTROOT" 
#read

#/usr/local/bak/adjust-home_doc-permissions

#echo -e \\n \\n Base of new tree  
find  -L . -name "PUBLIC" -type d -prune -print0 \
     |sed  -e 's/\PUBLIC//g' \
     |xargs -0 -i{} mkdir --parents "$DESTROOT/{}"
#we need -prune to cope with nested PUBLIC dirs
#find $DESTROOT |less

#echo -e \\n \\n Tree filled with symbolic links
# new in version 2.0: use nested find commands instead of 
# shell expansion:
find -L . -name "PUBLIC" -type d  -prune -print0 \
    |sed -e 's/\/PUBLIC//g' \
    |xargs -0 -i{2}  find  "$SOURCEROOT/{2}/PUBLIC/" -mindepth 1 -maxdepth 1 \
        -exec  ln -s "{}" "$DESTROOT/{2}" \;
#  we need -prune to cope with nested PUBLIC dirs


#  Find nested PUBLIC dirs and inform the user.
#  The linking above works with nested PUBLIC dirs, but
#  we consider them as an error.
COUNT=$( find -L "$DESTROOT" -name "PUBLIC" -print -quit | wc -l )    
if [  "$COUNT" == "1" ]; then
  echo -e "\n ***  Nested PUBLIC directories found: "
  find -L $DESTROOT -name "PUBLIC"     
  echo -e "\n ***  Assuming this is not what you want ... ABORT!"
  exit 1
fi

#find "$DESTROOT" 
#read
#exit 0





#now you can copy the resulting tree $DESTROOT on your webserer. 
#Keep in mind that your remote copy tool must resolve symbolic links, 
#that means it must copy the actual files not just the links to them.
#For example I use "unison" with the "follow" option.
#

