#!/usr/bin/env python
# Copyriht (c) 2019-2020 Qualcomm Technologies, Inc. All Rights Reserved.
# Proprietary and Confidential
import time

"""
This module contains python functions used by the SCons build system.

This module exports the function generate_linktime_paths, which is used to generate
a source file containing a list of const char [] definitions stating a path which is only known at
linktime. The source will be appended to a CA build by the offtarget CA builder.
"""

HEADER_STRING = '''
/*
 * Copyright (c) {year} Qualcomm Technologies, Inc.
 * All Rights Reserved.
 * Confidential and Proprietary - Qualcomm Technologies, Inc.
 *
 * Auto-generated file. Do not edit.
 */

'''

def exists(env):
  return env.Detect('generate_linktime_paths_file')

def generate(env):
  bld = env.Builder(action=generate_linktime_paths_file)
  env.Append(BUILDERS={'GenerateLinktimePathsFile' : bld})
  env.AddMethod(linktime_paths_list_to_source, 'LinktimePathsListToSource')
  env.AddMethod(source_to_linktime_paths_list, 'SourceToLinktimePathsList')

# Convert a list of (name, path) pairs to a source list. Store each element in each pair
# sequentially in the source list, essentially ending up with a flattened list.
# e.g. [('name', '/path/to/name'), ('name2', '/path/to/name2')] would be converted to:
#      ['name', '/path/to/name', 'name2', '/path/to/name2'] 
def linktime_paths_list_to_source(env, linktime_paths):
  ret = []
  for entry in linktime_paths:
    ret.append(env.Value(entry[0]))
    ret.append(env.Value(entry[1]))

  return ret

# Get original list back from source. The original list was a list of (name, path) pairs.
# See linktime_paths_list_to_source().
def source_to_linktime_paths_list(env, source):
  ret = []
  for i in range(0, len(source), 2):
    name = str(source[i])
    path = str(source[i + 1])
    ret.append((name, path))

  return ret

def generate_linktime_paths_file(env, source, target):
  """
  Generate .c file with list of 'const char []' declarations stating a path (e.g. to cmnlib) that
  is only known at linktime.
  """

  out_path = target[0].get_abspath()

  with open(out_path, 'w') as output_path:
    year = time.strftime("%Y")
    header = HEADER_STRING.format(year= year)
    output_path.write(header)

    linktime_paths_list = env.SourceToLinktimePathsList(source)

    for entry in linktime_paths_list:
      name = entry[0]
      path = env.RealPath(entry[1])
      # ???? RealPath() removes the trailing '/' ????
      if entry[1].endswith('/') and not path.endswith('/'):
        path = path + '/'
      
      path_definition_str = 'const char {name}[] = \"{path}\";\n'.format(name=name, path=path)
      output_path.write(path_definition_str)
