import re, sys

path = sys.argv[1]
with open(path) as f:
    content = f.read()

pattern = re.compile(
    r'(?P<add>^( *)git add environments/local/versions/kustomization\.yml services/overlays/local/kustomization\.yml\n)'
    r'(?P<commit>\2git commit -m "[^\n]*\n)',
    re.MULTILINE,
)

def repl(m):
    indent = m.group(2)
    add_line = m.group('add')
    commit_line = m.group('commit')
    guard = (
        f'{indent}if git diff --cached --quiet; then\n'
        f'{indent}  echo "No changes to commit -- a concurrent run for this exact commit already applied this bump. Nothing to push."\n'
        f'{indent}  return 0\n'
        f'{indent}fi\n'
    )
    return add_line + guard + commit_line

new_content, count = pattern.subn(repl, content)
if count != 1:
    print(f"UNEXPECTED MATCH COUNT {count} in {path}", file=sys.stderr)
    sys.exit(1)

with open(path, 'w') as f:
    f.write(new_content)
print(f"OK: patched {path}")
