import re


def _add_folders_to_path(path_line, folders_to_add_list):
  """Ensures that the given list of folders are inside the given line (for
  the PATH environment variable).

  Args:
    path_line(str): line in /etc/environment for the PATH environment variable
    folder_to_add_list(list of str): list of strings, where each string is a
      folder that must be present in the PATH environment variable. This list is
      assumed to be free of duplicate folders.

  Returns:
    (bool, str): The boolean value indicates if the line for the PATH
      environment variable has been modified; true means modified, false means
      not modified. The string value is the new line for the PATH environment
      variable, with all the folders in the `folders_to_add_list`
  """
  PATH_STRING_TEMPLATE = "PATH=\"{folders}\""

  # strip off surrounding quotes
  match_obj = re.match(r"""^PATH=['"]*(.*)$""", path_line)
  existing_folders_line = None
  if match_obj is None:
    return (True, PATH_STRING_TEMPLATE.format(
      folders=":".join(folders_to_add_list)
    ),)
  else:
    # strip trailing quotes.
    # We cannot just add a ['"]* to the above regex due to how greedy matching
    # works. It's possible to use non-greedy pattern matching but we do not do
    # that here.
    existing_folders_line = re.sub(r"""['"]*$""", "", match_obj.group(1))

  # obtain existing folders
  existing_folders_list = [
    folder for folder in existing_folders_line.split(":")
      if folder.strip() != ""
  ]
  existing_folders_set = set(existing_folders_list)
  path_line_modified = False
  for folder in folders_to_add_list:
    if folder not in existing_folders_set:
      path_line_modified = True
      existing_folders_list.append(folder)
      existing_folders_set.add(folder)
  return (path_line_modified, PATH_STRING_TEMPLATE.format(
    folders=":".join(existing_folders_list)
  ),)