#!/bin/sh
#
# Copyright (c) 2010  Peter Pentchev
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
#    notice, this list of conditions and the following disclaimer in the
#    documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``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 OR CONTRIBUTORS 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.

set -e

usage()
{
	cat <<EOUSAGE
Usage:	switch-link [-Nv] oldext newext
	switch-link [-h | -V]

	-h	display program usage information and exit
	-N	no-operation mode; display what would have been done
	-V	display program version information and exit
	-v	verbose mode; display diagnostic output

E.g.:	switch-link nonch ch
EOUSAGE
}

version()
{
	echo 'switch-link 0.01'
}

unset noop v opt_h opt_V
while getopts 'Nv' o; do
	case "$o" in
		h)
			opt_h=1
			;;

		N)
			noop='echo'
			;;

		V)
			opt_V=1
			;;

		v)
			v='-v'
			;;

		*)
			usage 1>&2
			exit 1
			;;
	esac
done

shift "`expr $OPTIND - 1`"

[ -z "$opt_V" ] || version
[ -z "$opt_h" ] || usage
[ -z "$opt_h$opt_V" ] || exit 0

if [ $# -ne 2 ]; then
	usage 1>&2
	exit 1
fi
oldext=".$1"
newext=".$2"

[ -z "$v" ] || echo "Changing $oldext to $newext" 1>&2
# FIXME: This really should be done with a temp file :)
for f in `find . -type l | sort`; do
	if [ ! -L "$f" ]; then
		echo "Bah, bogus link '$f' - space attack?" 1>&2
		continue
	fi
	[ -z "$v" ] || echo "Processing $f" 1>&2
	target=`readlink "$f"`
	if [ -z "$target" ]; then
		echo "readlink failed for $f" 1>&2
		continue
	fi
	[ -z "$v" ] || echo "- target $target" 1>&2
	base=`basename "$target" "$oldext"`
	[ -z "$v" ] || echo "- base $base" 1>&2
	if [ "$target" = "$base" ]; then
		[ -z "$v" ] || echo "- not ours, skipping" 1>&2
		continue
	fi

	newtgt="$base$newext"
	[ -z "$v" ] || echo "- new target $newtgt" 1>&2
	$noop ln -s -f $v "$newtgt" "$f"
done
