from util.dockerfileparse import parse_dockerfile, ParsedDockerfile, serialize_dockerfile

with open('Dockerfile.test', 'r') as dockerfileobj:
  parsed_dockerfile = parse_dockerfile(dockerfileobj.read())

quay_reponame = 'something'
env_command = {
  'command': 'ENV',
  'parameters': 'QUAY_REPOSITORY %s' % quay_reponame
}

for index, command in reversed(list(enumerate(parsed_dockerfile.commands))):
  if command['command'] == 'FROM':
    new_command_index = index + 1
    parsed_dockerfile.commands.insert(new_command_index, env_command)
    break

image_and_tag_tuple = parsed_dockerfile.get_image_and_tag()
print image_and_tag_tuple
if image_and_tag_tuple is None or image_and_tag_tuple[0] is None:
  raise Exception('Missing FROM command in Dockerfile')

print serialize_dockerfile(parsed_dockerfile)

with open('Dockerfile.test.out', 'w') as dockerfileobj:
  dockerfileobj.write(serialize_dockerfile(parsed_dockerfile))
