1#!/usr/bin/env python3
2#
3# SPDX-License-Identifier: GPL-2.0-only
4#
5
6import sys
7import os
8
9# Take a sysroot directory and turn all the abolute symlinks and turn them into
10# relative ones such that the sysroot is usable within another system.
11
12if len(sys.argv) != 2:
13    print("Usage is " + sys.argv[0] + "<directory>")
14    sys.exit(1)
15
16topdir = sys.argv[1]
17topdir = os.path.abspath(topdir)
18
19def handlelink(filep, subdir):
20    link = os.readlink(filep)
21    if link[0] != "/":
22        return
23    if link.startswith(topdir):
24        return
25    #print("Replacing %s with %s for %s" % (link, topdir+link, filep))
26    print("Replacing %s with %s for %s" % (link, os.path.relpath(topdir+link, subdir), filep))
27    os.unlink(filep)
28    os.symlink(os.path.relpath(topdir+link, subdir), filep)
29
30for subdir, dirs, files in os.walk(topdir):
31    for f in dirs + files:
32        filep = os.path.join(subdir, f)
33        if os.path.islink(filep):
34            #print("Considering %s" % filep)
35            handlelink(filep, subdir)
36