#!/usr/bin/perl -nl

=pod

extract-helmrelease-values

Extract the .spec.values from a HelmRelease yaml file, unindenting it and keeping the comments. That is, from

```
spec:
  values:
    foo
    bar
    # narf
    poit
```

print

```
foo
bar
# narf
poit
```

=cut

BEGIN {
    our $in_spec = 0;
    our $in_values = 0;
    our $just_entered_values = 0;
    our $values_indent;
}
if (! $in_spec) {
    # haven't entered .spec yet; keep an eye out but don't print anything
    if (/^spec:/) {
        $in_spec = 1;
    }
    next;
}
if (! $in_values) {
    # in spec but not in spec.values; keep an eye out but don't print anything
    if (/^(\s+)values:/) {
        $in_values = 1;
        $just_entered_values = 1;
    }
    next;
}
# We are in .spec.values. If we know what the indent is and find an
# appropriately indented line, unindent and print it.
if ($values_indent && /^${values_indent}(.+)$/) {
    print $1;
    next;
}
# If we find a line that's blank or just a comment, then print it
# even if it's not appropriately indented.
if (/^\s*(#|$)/) {
    print;
    next;
}
# If this is the first non-blank non-comment since .spec.values started, save
# the indent from it.
if ($just_entered_values) {
    if (/^(\s+)(\S.*)/) {
        $values_indent = $1;
        $just_entered_values = 0;
    }
    print $2;
    next;
}
# We have reached a non-blank non-comment line that's not sufficiently
# indented. This ends the block.
last;

