#!/bin/bash
#
# "ldd" wrapper for scratchbox 2, to be used in the "devel" mode
# (this wrapper requires that target tools are available
# at "/target_root")
#
# "ldd" is used to print shared libraries required by a program.
# Our problem is that it can be used to both host- and target
# binaries; this wrapper first detects the type of the binary,
# and then
#  - runs the "ldd" from /target_root for target binaries
#  - runs the binary with LD_TRACE_LOADED_OBJECTS=yes if
#    it is a host binary (there were to be problems running
#    the real "ldd" from inside sb2, but running ld.so
#    with that env.variable produces the required result)
#
# FIXME: Command line options only work with target binaries!
#
# Copyright (c) 2008 Nokia Corporation.
# All rights reserved.
# Author: Lauri T. Aarnio
#
# Licensed under GPL version 2

args="$*"
prog="$0"
progbase=`basename $0`

function error_not_inside_sb2()
{
	echo "SB2: $progbase wrapper: This wrapper can only be used from inside"
	echo "the scratchbox 2'ed environment"
	exit 1
}

if [ -z "$SBOX_SESSION_DIR" ]
then
	error_not_inside_sb2
fi

. $SBOX_SESSION_DIR/sb2-session.conf

if [ -z "$sbox_mapmode" -o -z "$sbox_dir" ]
then
	error_not_inside_sb2
fi

# read-in mode-specific settings
if [ -f $sbox_dir/share/scratchbox2/modeconf/sb2rc.$sbox_mapmode ]
then
	. $sbox_dir/share/scratchbox2/modeconf/sb2rc.$sbox_mapmode "$progbase"
fi

OPTIONS=""
FILES=""
NUM_FILES=0

for k in $args
do
	case $k in
	-*) OPTIONS="$OPTIONS $k";;
	*)  FILES="$FILES $k"
	    NUM_FILES=`expr $NUM_FILES + 1`;;
	esac
done

if [ $NUM_FILES -eq 0 ]
then
	exec /target_root/usr/bin/ldd $OPTIONS
fi

for f in $FILES
do
	if [ $NUM_FILES -gt 1 ]
	then
		echo "$f:"
	fi
	type=`sb2-show binarytype $f`
	case "$type" in
	target*) /target_root/usr/bin/ldd $OPTIONS $f;;
	host/dynamic*) LD_TRACE_LOADED_OBJECTS=yes $f;;
	*) echo "ldd wrapper: Don't know how to handle $f (type=$type)"
	esac
done

