1#!/bin/sh
2
3if [ "$#" -gt 1 ]; then
4    echo "Usage: $0 [path]"
5    echo "Run this script to relocate the buildroot SDK to the current location"
6    echo "If [path] is given, sets the location to [path] (without moving it)"
7    exit 1
8fi
9
10cd "$(dirname "$(readlink -f "$0")")"
11if [ "$#" -eq 1 ]; then
12    NEWPATH="$1"
13else
14    NEWPATH="${PWD}"
15fi
16
17LOCFILE="share/buildroot/sdk-location"
18if [ ! -r "${LOCFILE}" ]; then
19    echo "Previous location of the buildroot SDK not found!"
20    exit 1
21fi
22OLDPATH="$(cat "${LOCFILE}")"
23
24if [ "${NEWPATH}" = "${OLDPATH}" ]; then
25    echo "This buildroot SDK has already been relocated!"
26    exit 0
27fi
28
29# Check if the path substitution does work properly, e.g.  a tree
30# "/a/b/c" copied into "/a/b/c/a/b/c/" would not be allowed.
31newpath="$(sed -e "s|${OLDPATH}|${NEWPATH}|g" "${LOCFILE}")"
32if [ "${NEWPATH}" != "${newpath}" ]; then
33    echo "Something went wrong with substituting the path!"
34    echo "Please choose another location for your SDK!"
35    exit 1
36fi
37
38echo "Relocating the buildroot SDK from ${OLDPATH} to ${NEWPATH} ..."
39
40# Make sure file uses the right language
41export LC_ALL=C
42# Replace the old path with the new one in all text files
43grep -lr "${OLDPATH}" . | while read -r FILE ; do
44    if file -b --mime-type "${FILE}" | grep -q '^text/' && [ "${FILE}" != "${LOCFILE}" ]
45    then
46        sed -i "s|${OLDPATH}|${NEWPATH}|g" "${FILE}"
47    fi
48done
49
50# At the very end, we update the location file to not break the
51# SDK if this script gets interruted.
52sed -i "s|${OLDPATH}|${NEWPATH}|g" ${LOCFILE}
53