import tempfile


def write_temp_deploy(source_prototxt, batch_size):
  """
  Modifies an existing prototxt by adding force_backward=True and setting
  the batch size to a specific value. A modified prototxt file is written
  as a temporary file.
  
  Inputs:
  - source_prototxt: Path to a deploy.prototxt that will be modified
  - batch_size: Desired batch size for the network
  
  Returns:
  - path to the temporary file containing the modified prototxt
  """
  _, target = tempfile.mkstemp()
  with open(source_prototxt, 'r') as f:
    lines = f.readlines()
  force_back_str = 'force_backward: true\n'
  if force_back_str not in lines:
    lines.insert(1, force_back_str)

  found_batch_size_line = False
  with open(target, 'w') as f:
    for line in lines:
      if line.startswith('input_dim:') and not found_batch_size_line:
        found_batch_size_line = True
        line = 'input_dim: %d\n' % batch_size
      f.write(line)
  
  return target