#!/bin/bash
# Shadow a file in <dir> with another one
# Usage: altshadow <dir> <files...>
# Expects to find full path to file and file in the
#  shadow directory

if [ -z "$2" ]; then
	echo "Usage: altshadow <shadow dir> <files to shadow>"
fi

if ! [ -d "$1" ]; then
	echo "Can't find shadow directory!"
	exit 1
else
	if [ -z "$(grep $1 /proc/mounts)" ]; then
		echo "Shadow directory not mounted!"
		exit 1
	fi
fi
shadow="$1"
shift

for i in $@ ; do
	if [ $(expr substr "$i" 1 1) = '/' ]; then
	    # absolute path
	    myfile="$i"
	else
	    # assume relative path
	    myfile="$(pwd)/$i"
	fi

	if [ -a "${shadow}/$myfile" ]; then
		# Link the real thing to the shadow copy
		ln -sf "${shadow}/$myfile" "$myfile"
	else
		echo "Warning: shadow file for $myfile not found!"
		echo "Creating shadow copy from existing file."
		dir="$(dirname $myfile)"
		base="$(basename $myfile)"
		mkdir -p "${shadow}/${dir}"
		if [ -L "$myfile" ]; then
			ln -sf "${shadow}${myfile}" $(readlink "$myfile")
			ln -sf "$myfile" "${shadow}${myfile}"
		elif [ -f "$myfile" ]; then
			cp -p "$myfile" "${shadow}${dir}/"
			ln -sf "${shadow}$myfile" "$myfile"
		else
			echo "Can only shadow symlinks and regular files!"
			exit 1
		fi
	fi
done
