#!/bin/sh
#
# NAME
# link-dirs - create symlink mirror
#
# SYNOPSIS
# link-dirs src-dir dest-dir
#
# DESCRIPTION
#
# Recursively link the contents of the source dir to the
# destination dir. If the destination dir doesn't exist
# it will be created.
#
# Large portions written by the person under the name of jlevie on ExpertsExchange.

# A little paranoia is a good thing
if [ $# -ne 2 ]; then
  echo "Usage: link-dirs src-dir dest-dir"
  exit 1
fi
if [ ! -d $1 ]; then
   echo "Usage: link-dirs src-dir dest-dir"
   echo "      - src-dir doesn't exist"
   exit 1
fi

# Save the current dir.
curdir=`pwd`

# Create the destination dir, if it doesn't exist.
if [ ! -d $2 ]; then
  echo "Creating $2"
  mkdir $2
  if [ $? -ne 0 ]; then
    echo "Failed to create $2"
    exit 1
  fi
fi

# Get the absolute path to the new dir
cd $2
if [ $? -ne 0 ]; then
  exit 1
fi
dest=`pwd`
cd $curdir

# Change to the src dir
cd $1
if [ $? -ne 0 ]; then
  exit 1
fi
src=`pwd`

# Recursively create and subdirs

find . -type d |
while read d; do
  if [ $d != "." ]; then
    d=`echo $d | sed -e "s/\.\///"`
    if [ ! -d $dest/$d ]; then
      mkdir $dest/$d
      if [ $? -ne 0 ]; then
        echo "Failed to create $dest/$d"
        cd $curdir
        exit 1
      fi
    fi
  fi
done

# Recursively create links

find . -type f |
while read f; do
  f=`echo $f | sed -e "s/\.\///"`
  ln -s $src/$f $dest/$f
done

# Change back to the dir the command was invoked from
cd $curdir
