#!/bin/bash
# update-libtool-gcc.sh - update libtool to latest gcc release
#				optional -i to sed update libtool in place
#				optional full libtool path name
# requires bash for $HOSTTYPE and $OSTYPE

gcc_lib=/usr/lib/gcc		# default gcc library path name

# use sed -i to update libtool in place
[ $# -gt 0 ] && [ "-i" = "$1" ] && sed_opt=$1 && shift

# default full libtool path name
libtool_path=${@:-/usr/bin/libtool}

[ -x /usr/bin/errno ] \
    && notfound=$(/usr/bin/errno 2) \
    || notfound="ENOENT 2 No such file or directory"

# check libtool exists where specified
[ ! -x $libtool_path ]		&& \
    echo >&2 ${0##*/}: $libtool_path:		$notfound && exit 2

# check libtool writable if update in place
[ "-i" = "$1" ] && [ ! -w $libtool_path ]	&& \
    echo >&2 ${0##*/}: $libtool_path:		$notfound && exit 2

# check gcc library path exists where expected
[ ! -d $gcc_lib ]		&& \
    echo >&2 ${0##*/}: $gcc_lib:		$notfound && exit 2

# get host and OS specific library path
gcc_lib_path=$(/bin/ls -d $gcc_lib/$HOSTTYPE-*-$OSTYPE)

# check host and OS specific library path exists
[ ! -d $gcc_lib_path ]		&& \
    echo >&2 ${0##*/}: $gcc_lib_path:		$notfound && exit 2

# gcc host and OS version library path search pattern
gcc_lib_path_patt=$gcc_lib_path'/[0-9]\+\(\.[0-9]\+\)*'

# latest gcc host and OS version library path
latest_gcc_lib_path=$(/bin/ls -drv -- $gcc_lib_path/[0-9]* | \
		      /bin/grep -e "$gcc_lib_path_patt" -- | \
		      /usr/bin/head -n1 --)

# check latest gcc host and OS version library path exists
[ ! -d $latest_gcc_lib_path ]	&& \
    echo >&2 ${0##*/}: $latest_gcc_lib_path:	$notfound && exit 2

# build sed update command
update_gcc_lib_path='s!'"$gcc_lib_path_patt"'!'"$latest_gcc_lib_path"'!g'

# update libtool to check if changed and reapply update optionally in place
/bin/sed -e "$update_gcc_lib_path" -- $libtool_path		| \
/usr/bin/diff --brief --to-file=- -- $libtool_path > /dev/null	|| \
/bin/sed $sed_opt -e "$update_gcc_lib_path" -- $libtool_path

