#!/bin/sh
# ~jhs/bin/.sh/linkscheck
# http://www.berklix.com/~jhs/bin/.sh/linkscheck
# Purpose: Find accidental recursive links to self, from eg "ln -s mistake".
#	Useful to run this occasionaly perhaps before backups,
#	in case a file first needs to be rescued from a backup,
#	before an erroneous recursive link might propagate to backup.

# Does Not detect hanging links to non existant targets, do that by eg tar or
#	file shows "broken symbolic link to"
# Does not detect deliberately obscure erroneous links, eg via
#	/host/localhost/same-directory/same-name
# Script to make a test set & check:
#	mkdir linkscheck.tst ; cd linkscheck.tst ;
#	ln -s   bad.1
#	ln -s   bad.2	bad.2
#	ln -s ./bad.3
#	ln -s ./bad.4	bad.4
#	ln -s /tmp/ok.5	ok.5
#	ln -s ok.7	ok.6
#	cd .. ; linkscheck linkscheck.tst

# JJLATER cd ~jhs ; linkscheck does not descend into eg ./txt
# probably too many sym links at the top. for now do cd ~/txt/.. ; linkscheck

# for i in `find -s . -type l` ; do
# JJLATER why does this lists stuff twice eg Thing & ./Thing

# Could a veyr large tree maybe blow the max size of for loop below ?.

for i in `find -s * -type l` ; do
# JJLATER Fails to see eg .hidden_dir/Thing
# JJLATER Why is 360 seen twice in : cd ~/bin/.sh ; linkscheck ?
	target=`ls -l $i | awk -F ' -> ' '{printf "%s",$2}' `
	# echo "source : $i	target : $target"
	base=`basename $i`
	if [ "x$base" == "x$target" ] ; then     #{{
        	echo "$i"
        	# echo "$i `ls -l $i`"
	fi                              #}}
	# JJLATER merge these 2 Ifs.
	if [ "x./$base" == "x$target" ] ; then     #{{
        	echo "$i"
        	# echo "$i `ls -l $i`"
	fi                              #}}

	done
