
# version_settings() enforces a minimum Tilt version
# https://docs.tilt.dev/api.html#api.version_settings
version_settings(constraint='>=0.22.2')

def name(c):
  return c['metadata']['name']

def namespace(c):
  if 'namespace' in c['metadata']:
    return c['metadata']['namespace']
  return ''

def decode(yaml):
  resources = decode_yaml_stream(yaml)

  # workaround a bug in decode_yaml_stream where it returns duplicates
  # This bug has been fixed in Tilt v0.17.3+
  filtered = []
  names = {}
  for r in resources:
    if r == None:
      continue

    n = '%s:%s:%s' % (name(r), r['kind'], namespace(r))
    if n in names:
      continue

    names[n] = True
    filtered.append(r)

  return filtered

def find_overlapping(o, yamls):
  for elem in yamls:
    if name(o) == name(elem) and o['kind'] == elem['kind'] and namespace(o) == namespace(elem):
      return elem
  return None

yaml_objects = []
# Parse all YAML files in our "yamls" directory
for filename in listdir('yamls'):
  if filename.lower().endswith(('.yaml', '.yml')):
    decoded = decode(read_file(filename))
    for o in decoded:
      present = find_overlapping(o, yaml_objects)
      if present != None:
        print("Overlapping resource found: %s", filename)
        exit(1)
    yaml_objects += decoded

bundle = encode_yaml_stream(yaml_objects)

# k8s_yaml automatically creates resources in Tilt for the entities
# and will inject any images referenced in the Tiltfile when deploying
# https://docs.tilt.dev/api.html#api.k8s_yaml
k8s_yaml(bundle)
