1if ! xargs --version > /dev/null 2>&1; then
2	echo "xargs is required by the relocation script, please install it first. Abort!"
3	exit 1
4fi
5
6# fix dynamic loader paths in all ELF SDK binaries
7native_sysroot=$($SUDO_EXEC cat $env_setup_script |grep 'OECORE_NATIVE_SYSROOT='|cut -d'=' -f2|tr -d '"')
8dl_path=$($SUDO_EXEC find $native_sysroot/lib -name "ld-linux*")
9if [ "$dl_path" = "" ] ; then
10	echo "SDK could not be set up. Relocate script unable to find ld-linux.so. Abort!"
11	exit 1
12fi
13executable_files=$($SUDO_EXEC find $native_sysroot -type f \
14	\( -perm -0100 -o -perm -0010 -o -perm -0001 \) -printf "'%h/%f' ")
15if [ "x$executable_files" = "x" ]; then
16   echo "SDK relocate failed, could not get executalbe files"
17   exit 1
18fi
19
20tdir=`mktemp -d`
21if [ x$tdir = x ] ; then
22   echo "SDK relocate failed, could not create a temporary directory"
23   exit 1
24fi
25cat <<EOF >> $tdir/relocate_sdk.sh
26#!/bin/sh
27for py in python python2 python3
28do
29	PYTHON=\`which \${py} 2>/dev/null\`
30	if [ \$? -eq 0 ]; then
31		break;
32	fi
33done
34
35if [ x\${PYTHON} = "x"  ]; then
36	echo "SDK could not be relocated.  No python found."
37	exit 1
38fi
39\${PYTHON} ${env_setup_script%/*}/relocate_sdk.py $target_sdk_dir $dl_path $executable_files
40EOF
41
42$SUDO_EXEC mv $tdir/relocate_sdk.sh ${env_setup_script%/*}/relocate_sdk.sh
43$SUDO_EXEC chmod 755 ${env_setup_script%/*}/relocate_sdk.sh
44rm -rf $tdir
45if [ $relocate = 1 ] ; then
46	$SUDO_EXEC ${env_setup_script%/*}/relocate_sdk.sh
47	if [ $? -ne 0 ]; then
48		echo "SDK could not be set up. Relocate script failed. Abort!"
49		exit 1
50	fi
51fi
52
53# replace @SDKPATH@ with the new prefix in all text files: configs/scripts/etc.
54# replace the host perl with SDK perl.
55for replace in "$target_sdk_dir -maxdepth 1" "$native_sysroot"; do
56	$SUDO_EXEC find $replace -type f
57done | xargs -n100 file | grep ":.*\(ASCII\|script\|source\).*text" | \
58    awk -F':' '{printf "\"%s\"\n", $1}' | \
59    grep -Ev "$target_sdk_dir/(environment-setup-*|relocate_sdk*|${0##*/})" | \
60    xargs -n100 $SUDO_EXEC sed -i \
61        -e "s:$DEFAULT_INSTALL_DIR:$target_sdk_dir:g" \
62        -e "s:^#! */usr/bin/perl.*:#! /usr/bin/env perl:g" \
63        -e "s: /usr/bin/perl: /usr/bin/env perl:g"
64
65if [ $? -ne 0 ]; then
66	echo "Failed to replace perl. Relocate script failed. Abort!"
67	exit 1
68fi
69
70# change all symlinks pointing to @SDKPATH@
71for l in $($SUDO_EXEC find $native_sysroot -type l); do
72	$SUDO_EXEC ln -sfn $(readlink $l|$SUDO_EXEC sed -e "s:$DEFAULT_INSTALL_DIR:$target_sdk_dir:") $l
73	if [ $? -ne 0 ]; then
74		echo "Failed to setup symlinks. Relocate script failed. Abort!"
75		exit 1
76    fi
77done
78
79echo done
80