#!/bin/sh
#
# TODO (21.9.96) -
# <rwal@dowco.com> (Ray Walden) wrote:
# One thing I would like to have is a run-time option to allow deletion of
# stale links with no user interaction required. Scene here is that I started
# out with a canned cd-rom (linux-FT) release and then went with a whole-hog
# download-it-from-the-net upgrade - which left a LOT of stale sym links
# everywhere. Tidylinks came in really handy in cleaning this stuff up, but
# boy! were my donw-arrow and <Return> fingers worn out at the end of the day!

if echo $* | grep -wq "\-\-version" ; then
	echo "tidylinks version 1.16" 1>&2
	exit 0
fi

if echo $* | grep -wq "\-\-copyright" ; then
	cat <<EOF 1>&2
`sh "$0" --version`
by Stephen Kennedy, G0LRI
<steve@kalika.demon.co.uk>  http://www.kalika.demon.co.uk/sdk-software/

Based on v0.25+ of my zipdocdirs/zdd(8) script

Copyright (C) 1995-1996, S D K Software

All rights reserved.

Distribution and use of this script is permitted provided that the
following conditions are met:

 Distributions of this script must retain the above copyright
 notice, this list of conditions and the disclaimer below.
 If the script is modified it may be distributed provided this copyright
 notice is not removed and provided any changes you make are clearly marked.
 If the script is changed in any substantial way it must be distributed
 under a different name BUT with this copyright notice intact.
 Extracts of the script may be used in your work provided you include my
 copyright notice, list of conditions and disclaimer.

I also request, but do not insist, that the script is distributed together
with its manpage or, ideally, in its archive (package) form as released by
me and that you send any suggested changes to me for inclusion in the
"official" version.

THIS SOFTWARE IS PROVIDED BY THE AUTHOR \`\`AS IS'' AND ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO
EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
EOF
	exit 0
fi

if echo $* | grep -wq "\-\-help" ; then
	cat <<EOF
`sh "$0" --version 2>&1` - search for messy and dangling symbolic links.

Usage: tidylinks [options] [path ...]
Default path is the current directory.

Options:

--copyright
--help
--maxdepth,-m LEVELS	Descend LEVELS where LEVELS is a positive integer >0
--notidy,-N		Do not automatically tidy messy links
--textonly		Use standard tty text output rather than dialog
--version
--warn,-w		Just list messy and dangling links, don't do anything
			with them

EOF
	exit 0
fi



# Support for TARGET_DIR removed - too expensive in programming time for such
# little gain

TMP=${TMP:=/tmp}
OLDIFS="$IFS"

if [ ! -d "$TMP" ]; then
	mkdir -p "$TMP"
	chmod 1777 "$TMP"
fi

# maybe we imported a duff TMP or the mkdir failed:
if [ ! -d "$TMP" ] ; then
	echo "\"$TMP\" is NOT a directory. I need to have somewhere to store my working files, sorry\!" 1>&2
	logger -t tidylinks[$$] "\"$TMP\" - no such directory"
	exit 1
else
	TMP="$TMP/tidylinks.$$"
	mkdir "$TMP"
fi

if /bin/ls --no-colour / >/dev/null 2>&1 ; then
	ls() {
		/bin/ls --no-colour "$@"
	}
else
	ls() {
		/bin/ls "$@"
	}
fi

get_opts() {
	IFS="$OLDIFS"
	local OPTION
	while getopts m:NTw OPTION ; do
		case $OPTION in

			m) test $OPTARG -ge 0 2>/dev/null
			if [ $? != 0 ] ; then
				echo "You must specify a number with the maxdepth option." 1>&2
				exit 1
			elif [ $OPTARG -gt 0 ] ; then
				MAXDEPTH=$OPTARG
			fi ;;
# else MAXDEPTH stays at the default

			N) NOTIDY=1 ;;

			T) # TEXTONLY should already be set, but no harm in making sure!
			TEXTONLY=1 ;;

			w) WARNONLY=1 ;;

			*) sh "$0" --help 1>&2
			exit 1 ;;

		esac
	done
}

IFS='
'
# -T is undocumented and unsupported
get_opts $(for GET_OPTS in "$@" ; do echo $GET_OPTS | sed -e 's/--maxdepth=\|--maxdepth\>/-m/' -e 's/--notidy\>/-N/' -e 's/--textonly\>/-T/' -e 's/--warn\>/-w/' ; done)
shift $(expr $OPTIND - 1)
unset get_opts GET_OPTS
#


# If no `dialog` switch to TEXTONLY:
if [ ! "$TEXTONLY" ] && ! which dialog >/dev/null 2>&1 ; then
	echo "\`dialog\` not found - switching to \"--textonly\" mode" 1>&2
	TEXTONLY=1
fi

if [ "$WARNONLY" ] ; then
# save details for file then cat onto stdout (textonly) or via dialog
	fix_it() {
		if [ "$TEXTONLY" ] ; then
			cat <<EOF

Dangling link: "$LINKGOESIN/$LINKNAMEIS"
Reason: `echo "$1"`

EOF
		else
			cat <<EOF >>"$TMP/.stale_links"

Dangling link: "$LINKGOESIN/$LINKNAMEIS"
Reason: `echo "$1"`

EOF
		fi
	}
else
	if [ "$TEXTONLY" ] ; then
		tput clear
		read_input() {
			local INPUT
			read INPUT
			case "`echo $INPUT | tr A-Z a-z`" in

				"") echo "Null input. Try again"
				read_input ;;

				*nothing*|1) : ;;

				*dele*|2) echo "Deleting link..."
				rm -f "$LINKGOESIN/$LINKNAMEIS" ;;

				*modi*|3) echo "Input the new link destination (LINKPOINTSTO):"
				read LINKPOINTSTO
				if [ "$LINKPOINTSTO" = "" ] ; then
					echo "Null input. Skipping..."
				else
					ln -sf "$LINKPOINTSTO" "/$LINKGOESIN/$LINKNAMEIS"
					check_LINKPOINTSTO
				fi ;;

				*) echo "Invalid input. Try again"
				read_input ;;
			esac

			processing
		}
		fix_it() {
			printf \\007
			cat <<EOF

Dangling link: "$LINKGOESIN/$LINKNAMEIS"
Reason: `echo "$1"`

Please select one of the following actions:
 1	Do nothing
 2	Delete the link
 3	Modify the link

EOF
			read_input
		}
	else
		fix_it() {
			printf \\007
			dialog --title "tidylinks" --menu "Dangling link: \"$LINKGOESIN/$LINKNAMEIS\"\\nReason: $1\\nSelect one of the following options:\n" 17 80 4 \
Nothing "Do Nothing" \
Delete "Delete the link" \
Modify "Modify the link" \
Exit "Exit \`tidylinks\`" 2>"$TMP/reply" || { rm -f "$TMP/reply" "$TMP/links" "$TMP/linkname" 2>/dev/null; exit; }
			case `cat "$TMP/reply" ; rm -f "$TMP/reply" 2>/dev/null` in

				Nothing) : ;;

				Delete) echo "Deleting link..."
				rm -f "$LINKGOESIN/$LINKNAMEIS" ;;

				Modify) dialog --title "tidylinks" --inputbox "Dangling link: \"$LINKGOESIN/$LINKNAMEIS\"\\nReason: $1\\n\\nInput the new link destination (LINKPOINTSTO):" 11 70 2>"$TMP/LINKPOINTSTO" || { rm -f "$TMP/LINKPOINTSTO"; exit; }
				LINKPOINTSTO="`cat "$TMP/LINKPOINTSTO"`"
				rm -f "$TMP/LINKPOINTSTO" 2>/dev/null
				if [ "$LINKPOINTSTO" = "" ] ; then
					echo "Null input. Skipping..."
				else
					ln -sf "$LINKPOINTSTO" "/$LINKGOESIN/$LINKNAMEIS"
					check_LINKPOINTSTO
				fi ;;

				Exit) exit 0 ;;
			esac

			processing
		}
	fi
fi


# unless somebody wants to advise me differently, I am only issuing a warning
# for '/./' (obsolete) and not '/../' (relative path) :
if [ "$WARNONLY" -o "$NOTIDY" ] ; then
	is_messy() {
		if echo $LINKPOINTSTO | grep -Eq '\/\.\/|/{2,}' ; then
			if [ "$TEXTONLY" ] ; then
				echo "Messy link \"$LINKGOESIN/$LINKNAMEIS\""
			else
				echo "Messy link \"$LINKGOESIN/$LINKNAMEIS\"" >>"$TMP/.stale_links"
			fi
			LINKPOINTSTO="$(echo $LINKPOINTSTO | sed 's/\(\/\.\/\)\(\.\/\)*/\//g' | tr -s /)"
		fi
	}
else
	is_messy() {
		if echo $LINKPOINTSTO | grep -Eq '\/\.\/|/{2,}' ; then
			if [ "$TEXTONLY" ] ; then
				echo "Warning: Link \"$LINKGOESIN/$LINKNAMEIS\" was messy"
				ls -l "$LINKGOESIN/$LINKNAMEIS"
			else
				cat <<EOF >>"$TMP/.stale_links"
Warning: Link "$LINKGOESIN/$LINKNAMEIS" was messy
`ls -l "$LINKGOESIN/$LINKNAMEIS"`
EOF
			fi
			LGID=$(find "$LINKGOESIN/$LINKNAMEIS" -maxdepth 0 -printf %G)
			LUID=$(find "$LINKGOESIN/$LINKNAMEIS" -maxdepth 0 -printf %U)
			LINKPOINTSTO="$(echo $LINKPOINTSTO | sed 's/\(\/\.\/\)\(\.\/\)*/\//g'|tr -s /)"
			ln -sf "$LINKPOINTSTO" "$LINKGOESIN/$LINKNAMEIS"
			chown -f $LUID.$LGID "$LINKGOESIN/$LINKNAMEIS"
			if [ "$TEXTONLY" ] ; then
				echo "Tidied: `ls -l "$LINKGOESIN/$LINKNAMEIS"`"
			else
				echo "Tidied: `ls -l "$LINKGOESIN/$LINKNAMEIS"`" >>"$TMP/.stale_links"
			fi
		fi
	}
fi

check_LINKPOINTSTO() {
	if [ "`echo $LINKPOINTSTO | cut -b 1`" = "/" ] ; then # a full path :-)
		is_messy
		test -d "$(dirname "$LINKPOINTSTO")" || { fix_it "the directory which the \"$LINKNAMEIS\"\\nlink points to, \"$(dirname "$LINKPOINTSTO" | tr -s /)\",\\ndoes not exist."; return 0; }
	else # not a full path :-(
		if echo $LINKPOINTSTO | grep -q "\/" ; then # relative link
			is_messy
			if test -d "$LINKGOESIN/$(dirname "$LINKPOINTSTO")" ; then
				LINKPOINTSTO="$(echo $(cd "$LINKGOESIN/$(dirname "$LINKPOINTSTO")" ; pwd)/$(basename "$LINKPOINTSTO") | tr -s /)"
			else
				fix_it "the directory which the \"$LINKNAMEIS\"\\nlink points to, \"$(echo $LINKGOESIN/$(dirname "$LINKPOINTSTO") | sed 's/\(\/\.\/\)\(\.\/\)*/\//g')\",\\ndoes not exist."
				return 0
			fi
		else # must be a basename only
			LINKPOINTSTO="$LINKGOESIN/$LINKPOINTSTO"
		fi
	fi
	/usr/bin/test -e "$LINKPOINTSTO" || fix_it "\"$LINKPOINTSTO\" does NOT exist"
}

if [ "$TEXTONLY" ] ; then
	cat <<EOF

`sh "$0" --version 2>&1` by Stephen Kennedy, 1995-1996

Searching...

EOF
	processing() {
		sleep 1
		echo "Processing... Please wait"
	}
else
	processing() {
		sleep 1
		dialog --title "tidylinks" --infobox "Processing... Please wait" 3 70
	}
	dialog --title "tidylinks" --infobox "`sh "$0" --version 2>&1` by Stephen Kennedy, 1995-1996\\n\\nSearching..." 5 70
fi

if [ $# = 0 ] ; then
	path="`pwd`"
else
	path="$*"
	if test -L "$path" && [ "`find "$path" -xtype d 2>/dev/null`" = "" ] ; then
# path is a symlink not pointing to a directory
		BUTT=1
	fi
fi

GREEN_DAY=0
IFS='
'
# we use sed to add \ marks before characters which the shell would otherwise
# interpret as wildcards (e.g. I have, for good reason, a link called '?')
for LINK in $(if [ "$BUTT" ] ; then # path is a symlink not pointing to a dir
find "$path" -printf %p\\n%l\\n 2>/dev/null
else
[ "$(echo "$path" | cut -b-1)" != "/" ] && path="`pwd`/$path"
path="`echo "$path/" | tr -s /`"
if [ "$MAXDEPTH" ] ; then
find $path -path '/proc' -prune , ! -fstype proc ! -fstype iso9660 ! -fstype nfs ! -fstype smbfs -maxdepth $MAXDEPTH -type l -printf %p\\n%l\\n 2>/dev/null
else
find $path -path '/proc' -prune , ! -fstype proc ! -fstype iso9660 ! -fstype nfs ! -fstype smbfs -type l -printf %p\\n%l\\n 2>/dev/null
fi
fi | sed 's/\?/\\\?/' | sed 's/\*/\\\*/'
unset BUTT ; IFS="$OLDIFS") ; do

	if [ $GREEN_DAY = 0 ] ; then
		LINKNAMEIS="$(basename "$LINK")"
		LINKGOESIN="$(dirname "$LINK")"
		if echo "$LINK" | grep -q '\\' ; then
			LINEIS="Line contains a wildcard and/or back slash"
		else
			LINEIS="$(ls -dl "$LINK")"
		fi
		GREEN_DAY=1
	else
		if [ "$LINK" ] ; then # good
			LINKPOINTSTO="$LINK"
			check_LINKPOINTSTO
		else # bad
				echo "Skipping - caught an error:

$LINEIS" 1>&2
		fi
		GREEN_DAY=0
	fi
done
unset GREEN_DAY

if /usr/bin/test -e "$TMP/.stale_links" ; then
	printf \\007
	dialog --title "tidylinks results" --textbox "$TMP/.stale_links" 23 80
	rm -f "$TMP/.stale_links" 2>/dev/null
fi


rm -fr "$TMP" 2>/dev/null

echo "Done."
