1#!/usr/bin/env python
2# -*- coding: utf-8 -*-
3
4# Copyright (c) 2022-2023 Huawei Device Co., Ltd.
5#
6# HDF is dual licensed: you can use it either under the terms of
7# the GPL, or the BSD license, at your option.
8# See the LICENSE file in the root of this repository for complete details.
9
10
11import os
12import re
13from string import Template
14
15import hdf_utils
16from ..liteos.gn_file_add_config import analyze_parent_path
17
18
19def find_makefile_file_end_index(date_lines, model_name):
20    file_end_flag = "ccflags-y"
21    end_index = 0
22    model_dir_name = ("%s_ROOT_DIR" % model_name.upper())
23    model_dir_value = ""
24
25    for index, line in enumerate(date_lines):
26        if line.startswith("#"):
27            continue
28        elif line.strip().startswith(file_end_flag):
29            end_index = index
30            break
31        elif line.strip().startswith(model_dir_name):
32            model_dir_value = line.split("=")[-1].strip()
33        else:
34            continue
35    result_tuple = (end_index, model_dir_name, model_dir_value)
36    return result_tuple
37
38
39def formate_mk_config_build(source_path, date_lines, devices, root):
40    if len(source_path) > 1:
41        sources_line = []
42        obj_first_line = "\nobj-$(CONFIG_DRIVERS_HDF_${model_name_upper}_${driver_name_upper}) += \\\n"
43        temp_line = "\t\t\t\t$(${file_parent_path})/${source_path}.o"
44        for source in source_path:
45            temp_handle = Template(temp_line.replace("$(", "temp_flag"))
46            temp_dict = analyze_parent_path(
47                date_lines, source, "", devices, root)
48            try:
49                temp_dict['source_path'] = temp_dict.get(
50                    'source_path').strip(".c")
51            except KeyError as _:
52                continue
53            finally:
54                pass
55            if source == source_path[-1]:
56                sources_line.append("".join([temp_handle.substitute(
57                    temp_dict).replace("temp_flag", "$("), "\n"]))
58            else:
59                sources_line.append("".join([temp_handle.substitute(
60                    temp_dict).replace("temp_flag", "$("), " \\", "\n"]))
61        build_resource = obj_first_line + "".join(sources_line)
62    else:
63        build_resource = "LOCAL_SRCS += $(${file_parent_path})/${source_path}\n"
64        for source in source_path:
65            temp_handle = Template(build_resource.replace("$(", "temp_flag"))
66            temp_dict = analyze_parent_path(
67                date_lines, source, "", devices, root)
68            build_resource = temp_handle.substitute(temp_dict).replace("temp_flag", "$(")
69    return build_resource
70
71
72def audio_makefile_template(date_lines, driver, source_path, head_path, devices, root):
73    judge_result = judge_driver_config_exists(date_lines, driver_name=driver)
74    if judge_result:
75        return
76    sources_lines = []
77    obj_first_line = "\nobj-$(CONFIG_DRIVERS_HDF_${model_name_upper}_${driver_name_upper}) += \\\n"
78    temp_line = "        ${source_path}.o"
79    for source in source_path:
80        temp_handle = Template(temp_line.replace("$(", "temp_flag"))
81        temp_dict = analyze_parent_path(
82            date_lines, source, "", devices, root)
83        try:
84            temp_dict['source_path'] = temp_dict.get(
85                'source_path').strip(".c")
86        except KeyError as _:
87            continue
88        finally:
89            pass
90        if source == source_path[-1]:
91            sources_lines.append(temp_handle.substitute(temp_dict).replace("temp_flag", "$("))
92        else:
93            temp_replace_str = temp_handle.substitute(temp_dict).replace("temp_flag", "$(")
94            sources_lines.append("{} \\\n".format(temp_replace_str))
95    build_resource = "{}{}".format(obj_first_line, "".join(sources_lines))
96    head_line = []
97    ccflags_first_line = "\nccflags-$(CONFIG_DRIVERS_HDF_${model_name_upper}_${driver_name_upper}) += \\\n"
98    temp_line = "        -I$(srctree)/$(${file_parent_path})/${head_path}"
99    for head_file in head_path:
100        temp_handle = Template(temp_line.replace("$(", "temp_flag"))
101        temp_dict = analyze_parent_path(
102            date_lines, "", head_file, devices, root)
103        if head_file == head_path[-1]:
104            temp_str = "".join([temp_handle.substitute(
105                temp_dict).replace("temp_flag", "$("), "\n"])
106        else:
107            temp_str = "".join([temp_handle.substitute(
108                temp_dict).replace("temp_flag", "$("), " \\", "\n"])
109        head_line.append(temp_str)
110    build_head = ccflags_first_line + "".join(head_line)
111    makefile_add_template = build_resource + build_head
112    return makefile_add_template
113
114
115def audio_linux_makefile_operation(path, args_tuple):
116    source_path, head_path, module, driver, root, devices, board = args_tuple
117    makefile_gn_path = path
118    mk_re_str = r"CONFIG_DRIVERS_HDF_(?P<name>.+[A-Z0-9])"
119    flag_re = r"obj"
120    sign_str = "(KHDF_AUDIO_BASE_ROOT_DIR)/device/board/"
121    temp_file = hdf_utils.MakefileAndKconfigFileParse(
122        file_path=makefile_gn_path, flag_str=flag_re, re_name=mk_re_str)
123    board_makefile_dict = {}
124    for block_info in temp_file.split_target_block(flag_re):
125        if block_info.find(sign_str) > 0:
126            board_name = re.search(mk_re_str, block_info).group()
127            board_makefile_dict[board_name] = re.findall(
128                r"\(KHDF_AUDIO_BASE_ROOT_DIR\)/device/board/[a-z0-9_/]+", block_info)[0]
129    if board.startswith("rk3568"):
130        parent_str = board_makefile_dict.get("CONFIG_DRIVERS_HDF_AUDIO_RK3568")
131    elif board.startswith("hispark_taurus"):
132        parent_str = board_makefile_dict.get("CONFIG_DRIVERS_HDF_AUDIO_HI3516CODEC")
133    temp_makefile = "/".join(parent_str.split("/")[1:])
134    makefile_path = os.path.join(root, temp_makefile, "Makefile")
135    date_lines = hdf_utils.read_file_lines(makefile_path)
136    makefile_add_template = audio_makefile_template(
137        date_lines, driver, source_path, head_path, devices, root)
138
139    temp_handle = Template(makefile_add_template.replace("$(", "temp_flag"))
140    temp_replace = {
141        'model_name_upper': module.upper(),
142        'driver_name_upper': driver.upper(),
143    }
144    new_line = temp_handle.substitute(temp_replace).replace("temp_flag", "$(")
145    date_lines = date_lines + [new_line]
146    hdf_utils.write_file_lines(makefile_path, date_lines)
147    return makefile_path
148
149
150def judge_driver_config_exists(date_lines, driver_name):
151    for _, line in enumerate(date_lines):
152        if line.startswith("#"):
153            continue
154        elif line.find(driver_name) != -1:
155            return True
156    return False
157
158
159def linux_makefile_operation(path, driver_file_path, head_path, module, driver):
160    makefile_gn_path = path
161    date_lines = hdf_utils.read_file_lines(makefile_gn_path)
162    source_file_path = driver_file_path.replace('\\', '/')
163    result_tuple = find_makefile_file_end_index(date_lines, model_name=module)
164    judge_result = judge_driver_config_exists(date_lines, driver_name=driver)
165    if judge_result:
166        return
167    end_index, model_dir_name, model_dir_value = result_tuple
168
169    if module == "sensor":
170        first_line = "\nobj-$(CONFIG_DRIVERS_HDF_${model_name_upper}_${driver_name_upper}) += \\\n"
171        second_line = "              $(SENSOR_ROOT_CHIPSET)/${source_file_path}\n"
172        third_line = "\n"
173        makefile_add_template = first_line + second_line + third_line
174        temp_handle = Template(makefile_add_template.replace("$(", "temp_flag"))
175        str_start = source_file_path.find(module) + len(module) + 1
176        temp_replace = {
177            'model_name_upper': module.upper(),
178            'driver_name_upper': driver.upper(),
179            'source_file_path': source_file_path[str_start:].replace(".c", ".o")
180        }
181    else:
182        first_line = "\nobj-$(CONFIG_DRIVERS_HDF_${model_name_upper}_${driver_name_upper}) += \\\n"
183        second_line = "              $(${model_name_upper}_ROOT_DIR)/${source_file_path}\n"
184        third_line = "ccflags-y += -I$(srctree)/drivers/hdf/framework/model/${head_file_path}\n"
185        makefile_add_template = first_line + second_line + third_line
186        include_model_info = model_dir_value.split("model")[-1].strip('"') + "/"
187        makefile_path_config = source_file_path.split(include_model_info)
188        temp_handle = Template(makefile_add_template.replace("$(", "temp_flag"))
189        temp_replace = {
190            'model_name_upper': module.upper(),
191            'driver_name_upper': driver.upper(),
192            'source_file_path': makefile_path_config[-1].replace(".c", ".o"),
193            'head_file_path': '/'.join(head_path.split("model")[-1].strip(os.path.sep).split(os.path.sep)[:-1])
194        }
195    new_line = temp_handle.substitute(temp_replace).replace("temp_flag", "$(")
196    endif_status = False
197    for index, v in enumerate(date_lines[::-1]):
198        if v.strip().startswith("endif"):
199            endif_status = True
200            end_line_index = len(date_lines) - index - 1
201            date_lines = date_lines[:end_line_index] + [new_line] + [date_lines[end_line_index]]
202            break
203    if not endif_status:
204        date_lines = date_lines + [new_line]
205    hdf_utils.write_file_lines(makefile_gn_path, date_lines)
206