#!/bin/sh
# Script to remove cross-directory hard links from a directory tree,
# to make it suitable for mirroring into AFS.

# Produce a list of files with hard links, sorted by inode and then by
# directory, then separate file name and directory name.

find . -type f ! -links 1 -print | xargs ls -i | sort +2 | sort -ns \
	| sed 's#/\([^/]*\)$# \1#' \
	| while read inode dir file; do
	if [ "$inode" != "$previnode" ]; then
		previnode=$inode
		prevdir=$dir
		origfile=$file
		newdir=no
		continue
	fi
	if [ "$dir" != "$prevdir" ]; then
		echo "Breaking link from $prevdir/$origfile to $dir/$file"
		rm $dir/$file
		cp -p $prevdir/$origfile $dir/$file
		prevdir=$dir
		origfile=$file
		newfile=$dir/$file
		newdir=yes
		continue
	fi
	if [ "$newdir" = yes ]; then
		echo "Linking $dir/$file to $newfile"
		rm $dir/$file
		ln $newfile $dir/$file
	fi
done
