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