#!/bin/bash
##
## $1 = install :
## Replace various system files with symlinks to their replacements
## as found within the directory heirarchy given by "$2".
## The originals also stay put, renamed with a .real suffix.
##
## $1 = restore :
## Try to put things back to normal again.
## 

function install_sysfiles(){
	while read sysfile ; do
		target=
		if [ -L "/$sysfile" ]; then
			target="`readlink /$sysfile`"
			[ "$target" = "$1/$sysfile" ] && continue
		fi
		[ -e "/$sysfile" ] && mv -f "/$sysfile" "/$sysfile.real"
		[ "$target" != "DELETED" ] && ln -s "$1/$sysfile" "/$sysfile"
	done
}

function restore_sysfiles(){
	while read sysfile ; do
		if [ -L "/$sysfile" ]; then
			target="`readlink /$sysfile`"
			if [ "$target" = "DELETED" -a ! -e "/$sysfile" ]; then
				[ -e "/$sysfile.real" ] && mv -f "/$sysfile.real" "/$sysfile"
			else
				if [ "$target" = "$1/$sysfile" ]; then
					rm -f "/$sysfile"
					[ -e "/$sysfile.real" ] && mv -f "/$sysfile.real" "/$sysfile"
				fi
			fi
		fi
	done
}

action="$1"
if [ "$action" != "install" -a "$action" != "restore" ]; then
	echo "$action: bad action parm"
	exit 1
fi

srcdir="$2"
if [ ! -d "$srcdir" ]; then
	echo "$srcdir: not a directory"
	exit 2
fi

cd "$srcdir" || exit 3
for dir in * ; do
	[ -d $dir ] && find -L "$dir" -type f | ${action}_sysfiles "$srcdir"
done
exit 0
