#!/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.   

SOURCEROOT="/usr/local/document-base/"


DESTROOT="/tmp/Public-Documents2"


# Public sha256 sums of this dir
MD5SUMDIR="$DESTROOT/public"





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



# Calculate md5sums
cd $MD5SUMDIR

find -L "." -type f \( -path "*/.*" -prune -o  -print0 \) |\
          sort -z | xargs -0 -I {}  sha256sum {}  >"sha256sum.txt"

