1#!/usr/bin/python3
2
3import subprocess
4import tempfile
5import os
6from os.path import join, getsize
7import argparse
8
9# Set command line arguments
10parser = argparse.ArgumentParser(
11            formatter_class=argparse.ArgumentDefaultsHelpFormatter)
12
13parser.add_argument("-b", "--build_dir",
14                    dest="BUILD_DIR",
15                    default="/home/ed/openbmc-openbmc",
16                    help="Build directory path.")
17
18parser.add_argument("-s", "--squashfs_file",
19                    dest="SQUASHFS_FILE",
20                    default="/build/tmp/deploy/images/wolfpass" +
21                    "/intel-platforms-wolfpass.squashfs-xz",
22                    help="Squashfs file.")
23
24args = parser.parse_args()
25
26# files below this size wont be attempted
27FILE_SIZE_LIMIT = 0
28
29SQUASHFS = args.BUILD_DIR + args.SQUASHFS_FILE
30
31original_size = getsize(SQUASHFS)
32print ("squashfs size: {}".format(original_size))
33
34results = []
35
36with tempfile.TemporaryDirectory() as tempremovedfile:
37    with tempfile.TemporaryDirectory() as tempsquashfsdir:
38        print("writing to " + tempsquashfsdir)
39        command = ["unsquashfs", "-d",
40                   os.path.join(tempsquashfsdir, "squashfs-root"),  SQUASHFS]
41        print(" ".join(command))
42        subprocess.check_call(command)
43        squashfsdir = tempsquashfsdir + "/squashfs-root"
44
45        files_to_test = []
46        for root, dirs, files in os.walk(squashfsdir):
47            for name in files + dirs:
48                filepath = os.path.join(root, name)
49                if not os.path.islink(filepath):
50                    # ensure files/dirs can be renamed
51                    os.chmod(filepath, 0o711)
52                    if getsize(filepath) > FILE_SIZE_LIMIT:
53                        files_to_test.append(filepath)
54
55        print("{} files to attempt removing".format(len(files_to_test)))
56
57        for filepath in files_to_test:
58            name = os.path.basename(filepath)
59            newname = os.path.join(tempremovedfile, name)
60            os.rename(filepath, newname)
61            with tempfile.TemporaryDirectory() as newsquashfsroot:
62                subprocess.check_output(
63                    ["mksquashfs", tempsquashfsdir,
64                     newsquashfsroot + "/test", "-comp", "xz"])
65
66                results.append((filepath.replace(squashfsdir, ""),
67                                original_size -
68                                getsize(newsquashfsroot + "/test")))
69
70            os.rename(newname, filepath)
71
72            print("{:>6} of {}".format(len(results), len(files_to_test)))
73
74results.sort(key=lambda x: x[1], reverse=True)
75
76with open("results.txt", 'w') as result_file:
77    for filepath, size in results:
78        result = "{:>10}: {}".format(size, filepath)
79        print(result)
80        result_file.write(result + "\n")
81