1#!/usr/bin/env python
2# -*- coding: utf-8 -*-
3# Copyright (c) 2021 Huawei Device Co., Ltd.
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8#     http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15
16import argparse
17import sys
18import os
19import shutil
20import tarfile
21
22sys.path.append(
23    os.path.dirname(os.path.dirname(os.path.dirname(
24        os.path.abspath(__file__)))))
25from scripts.util import build_utils  # noqa: E402
26
27
28def merge_image_files(src_image_path: str, dest_image_path: str):
29    if not os.path.exists(src_image_path):
30        raise Exception(
31            "source image path {} does not exist.".format(src_image_path))
32
33    for root, dirs, files in os.walk(src_image_path):
34        for dir_name in dirs:
35            src_dir = os.path.join(root, dir_name)
36            dir_relpath = os.path.relpath(src_dir, src_image_path)
37            dest_dir_path = os.path.join(dest_image_path, dir_relpath)
38            if not os.path.exists(dest_dir_path):
39                os.makedirs(dest_dir_path, exist_ok=True)
40
41        for file_name in files:
42            src_file_path = os.path.join(root, file_name)
43            file_relpath = os.path.relpath(src_file_path, src_image_path)
44            dest_file_path = os.path.join(dest_image_path, file_relpath)
45            if not os.path.exists(dest_file_path):
46                if not os.path.exists(os.path.dirname(dest_file_path)):
47                    os.makedirs(os.path.dirname(dest_file_path), exist_ok=True)
48                shutil.copy2(src_file_path, dest_file_path)
49
50
51def compress_image_files(package_dir: str, output_file: str, additional_files: list):
52    # Compress the image folder
53    files = [package_dir] + additional_files
54    with tarfile.open(output_file, "w:gz") as tar:
55        for f in files:
56            if os.path.exists(f):
57                try:
58                    # additional files will be packed outside of system dir.
59                    if f in additional_files:
60                        tar.add(f, arcname=os.path.basename(f))
61                    else:
62                        tar.add(f, arcname='system')
63                except OSError as ioerr:
64                    print("Compress file failed. Error code: {}".format(
65                        ioerr.errno))
66                except:
67                    print("Unexpected error")
68                    raise
69
70
71def main(argv):
72    argv = build_utils.expand_file_args(argv)
73    parser = argparse.ArgumentParser()
74    build_utils.add_depfile_option(parser)
75    parser.add_argument('--image-dir', help='', required=True)
76    parser.add_argument("--system-image-zipfile", required=True)
77    parser.add_argument('--output-file', help='', required=True)
78    parser.add_argument('--additional-files', help='', action='append')
79    args = parser.parse_args(argv[1:])
80
81    depfiles = [args.system_image_zipfile] + args.additional_files
82    with build_utils.temp_dir() as img_dir:
83        build_utils.extract_all(args.system_image_zipfile,
84                                img_dir,
85                                no_clobber=True)
86        build_utils.call_and_write_depfile_if_stale(
87            lambda: compress_image_files(img_dir, args.output_file, args.
88                                         additional_files),
89            args,
90            depfile_deps=depfiles,
91            input_paths=depfiles,
92            output_paths=([args.output_file]),
93            force=False,
94            add_pydeps=False)
95
96
97if __name__ == "__main__":
98    main(sys.argv)
99