1#!/usr/bin/env python3
2# -*- coding: utf-8 -*-
3# Copyright (c) 2023 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
16
17import subprocess
18import argparse
19import os
20import sys
21import shlex
22
23
24def parse_args(args):
25    parser = argparse.ArgumentParser()
26    parser.add_argument('--sdk-out-dir')
27    options = parser.parse_args(args)
28    return options
29
30
31def sign_sdk(zipfile, sign_list, sign_results):
32    if zipfile.endswith('.zip'):
33        sign = os.getenv('SIGN')
34        if not sign:
35            raise AttributeError(f"SIGN message not in env")
36        dir_name = zipfile.split('-')[0]
37        cmd1 = ['unzip', "-q", zipfile]
38        subprocess.call(cmd1)
39        need_sign_files = []
40        for root, dirs, files in os.walk(dir_name):
41            for file in files:
42                file = os.path.join(root, file)
43                need_sign_files.append(file)
44        for file in need_sign_files:
45            if file.split('/')[-1] in sign_list or file.endswith('.so') or file.endswith('.dylib') \
46                    or file.split('/')[-2] == 'bin':
47                cmd2 = ['codesign', '-fs', sign, '--timestamp', '--options=runtime', file]
48                subprocess.call(cmd2)
49        cmd3 = ['rm', zipfile]
50        subprocess.call(cmd3)
51        cmd4 = ['zip', '-rq', zipfile, dir_name]
52        subprocess.call(cmd4)
53        cmd5 = ['rm', '-rf', dir_name]
54        subprocess.call(cmd5)
55        mac_machine = subprocess.run(['uname', '-m'], stdout=subprocess.PIPE, text=True)
56        if mac_machine.stdout.strip() in ['arm64', 'aarch64']:
57            ohos_name = shlex.quote("ohos-sdk")
58        elif mac_machine.stdout.strip() in ['x86_64', 'amd64', 'Intel64']:
59            ohos_name = "ohos-sdk"
60        else:
61            print('Submit fail, because machine is not mac. Please check your compilation command')
62            return
63        cmd6 = ['xcrun', 'notarytool', 'submit', zipfile, '--keychain-profile', ohos_name, '--no-s3-acceleration']
64        process = subprocess.Popen(cmd6, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
65        sign_results.append((cmd6, process))
66
67
68def main(args):
69    options = parse_args(args)
70    darwin_sdk_dir = os.path.join(options.sdk_out_dir, 'darwin')
71    os.chdir(darwin_sdk_dir)
72    sign_list = ['lldb-argdumper', 'fsevents.node', 'idl', 'restool', 'diff', 'ark_asm',
73                 'ark_disasm', 'hdc', 'syscap_tool', 'hnpcli', 'rawheap_translator']
74    sign_results = []
75    for file in os.listdir('.'):
76        sign_sdk(file, sign_list, sign_results)
77    for cmd, process in sign_results:
78        try:
79            stdout, stderr = process.communicate(timeout=3600)
80            if process.returncode:
81                print(f"cmd:{' '.join(cmd)}, result is {stdout}")
82                raise Exception(f"run command {' '.join(cmd)} fail, error is {stderr}")
83        except Exception as e:
84            raise TimeoutError(r"run xcrun cmd timeout")
85
86
87if __name__ == '__main__':
88    sys.exit(main(sys.argv[1:]))
89