#!/usr/bin/env python

import re,sys,yaml
import os.path

dockerfileInFile = "Dockerfile.in"
dockerfileOut = "Dockerfile"
metaFile = "origin-meta.yaml"

if len(sys.argv) > 1:
  dockerfileInFile =  sys.argv[1]
if len(sys.argv) > 2:
  dockerfileOut =  sys.argv[2]

with open(dockerfileInFile, 'r') as f:
  dockerfileIn = f.read()

metaFile = os.path.join(os.path.dirname(dockerfileInFile), metaFile)
with open(metaFile, 'r') as f:
  metaYaml = yaml.safe_load(f)

froms = metaYaml['from']
if froms and len(froms) > 0:
  for base in froms:
    dockerfileIn = re.sub("FROM " + base['source'],"FROM " + base['target'],dockerfileIn)

#Remove aliases if only one is defined otherwise it will fail
aliases = []
for l in dockerfileIn.split("\n"):
  if l.startswith("FROM"):
    index = l.rfind("AS")
    if index > -1:
      aliases.append(l[index + 3:])
if len(aliases) == 1:
  dockerfileIn = re.sub("--from=" + aliases[0],"",dockerfileIn)

exclude = False
print("### This is a generated file from Dockerfile.in ###")
for l in dockerfileIn.split('\n'):
  if l == "## EXCLUDE BEGIN ##":
    exclude = True
    continue
  if l == "## EXCLUDE END ##":
    exclude = False
    continue
  if not exclude:
    print(l)
