#!/bin/sh
# Identify links to a file
# Usage: links file [directory]

if [ $# -eq 0 -o $# -gt 2 ]; then
	echo "Usage: links file [directory]" 1>&2
	exit 1
fi
if [ -d "$1" ]; then
	echo "First argument cannot be a directory." 1>&2
	echo "Usage: links file [directory]" 1>&2
	exit 1
else
	file="$1"
fi
if [ $# -eq 1 ]; then
	directory="."
elif [ -d "$2" ]; then
	directory="$2"
else
	echo "Optional second argument must be a directory." 1>&2
	echo "Usage: links file [directory]" 1>&2
	exit 1
fi

# Check to make sure file exists and is a regular file:
if [ ! -f "$file" ]; then
	echo "links: $file not found or special file" 1>&2
	exit 1
fi
# Check link count on file
set -- `ls -l "$file"`
linkcnt=$2
if [ "$linkcnt" -eq 1 ]; then
	echo "links: no other links to $file" 1>&2
	exit 0
fi

# Get the inode of the given file
set `ls -i "$file"`
inode=$1

# Find and print the files with that inode number
echo "links: using find to search for links..." 1>&2
find "$directory"  -xdev -inum $inode -print
