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
20sys.path.append(
21    os.path.dirname(os.path.dirname(os.path.dirname(
22        os.path.abspath(__file__)))))
23from scripts.util import build_utils  # noqa: E402
24from scripts.util import file_utils  # noqa: E402
25
26
27def archive_files(system_image_zipfile: str, additional_files: list, output_dir: str,
28                  output_file: str):
29    if not os.path.exists(output_dir):
30        os.makedirs(output_dir, exist_ok=True)
31
32    build_utils.extract_all(system_image_zipfile, os.path.join(output_dir, "system"),
33                            no_clobber=False)
34    for _file in additional_files:
35        _dest = os.path.join(output_dir, os.path.basename(_file))
36        if os.path.isdir(_file):
37            if os.path.exists(_dest):
38                shutil.rmtree(_dest)
39            shutil.copytree(_file, _dest)
40        else:
41            shutil.copy2(_file, _dest)
42
43    files_list = []
44    for root, _, files in os.walk(output_dir):
45        for _file in files:
46            files_list.append(os.path.join(root, _file))
47    file_utils.write_file(output_file, '\n'.join(files_list))
48
49
50def main(argv):
51    argv = build_utils.expand_file_args(argv)
52    parser = argparse.ArgumentParser()
53    build_utils.add_depfile_option(parser)
54    parser.add_argument("--system-image-zipfile", required=True)
55    parser.add_argument('--output-dir', required=True)
56    parser.add_argument('--output-file', required=True)
57    parser.add_argument('--additional-files', action='append')
58    args = parser.parse_args(argv[1:])
59
60    depfiles = [args.system_image_zipfile] + args.additional_files
61    build_utils.call_and_write_depfile_if_stale(
62        lambda: archive_files(args.system_image_zipfile, args.additional_files,
63                              args.output_dir, args.output_file),
64        args,
65        depfile_deps=depfiles,
66        input_paths=depfiles,
67        output_paths=([args.output_file, args.output_dir]),
68        force=False,
69        add_pydeps=False)
70
71
72if __name__ == "__main__":
73    main(sys.argv)
74