#!/bin/bash

#mirrorlinks 1.0.0, under the GPL, copyright Rudd-O

if [ "$1" == "" ] ; then
	echo "usage: $0 [-r] src-dir [dest-dir]"
	echo ""
	echo "mirrorlinks - create a mirror of a directory composed exclusively of symlinks and folders"
	echo "dest-dir is optional and defaults to the current directory"
	echo "mirrorlinks requires python to be installed"
	echo ""
	echo "options:"
	echo "  -r:	delete existing files on the destination directory"
	echo "  	matching source files on the source directory"
	exit 1
fi

if [ "$1" == "-r" ] ; then
	deleteexisting="1"
	srcdir="$2"
	destdir="$3"
else
	deleteexisting=""
	srcdir="$1"
	destdir="$2"
fi

if [ "$destdir" == "" ] ; then destdir=`pwd` ; fi

abspathprog="#!/usr/bin/env python

import os
import sys

print os.path.abspath(sys.argv[1])"

srcdir=`echo "$abspathprog" | python - "$srcdir"`
destdir=`echo "$abspathprog" | python - "$destdir"`

if [ "$srcdir" == "$destdir" ] ; then
	echo "mirrorlinks: error: the source and destination directories are the same"
	echo "obviously, this isn't what you wanted"
	exit 1
fi

cd "$srcdir"
filelist=`find . | grep -v '/\.svn' | sed 's/^\.\///g' | sed 's/^\.$//g' | grep -v '^$' `

# filelist=`echo "$filelist" | sed 's/\\\/\\\\\\\/g' | sed 's/"/\\\"/g'  | sed 's/^/"/g' | sed 's/$/"/g'`

cd "$OLDPWD"

export IFS=$'\n'
for file in $filelist ; do
	srcfile="$srcdir/$file"
	destfile="$destdir/$file"
	if [ -d "$srcfile" ] ; then
		mkdir -p "$destfile" || exit 4
	else
		if [ "$deleteexisting" != "" ] ; then
			rm -rf "$destfile" || exit 3
		fi
		ln -s "$srcfile" "$destfile" || exit 2
	fi
done


