#!/usr/bin/env python3
"""Replace the leading '#' comment block of a text/YAML file by a supplied header and drop
in-line YAML comment-only lines flagged as internal; verify that every non-comment line is
byte-identical and in the same order.  usage: scrub_header.py IN OUT HEADERFILE"""
import sys
from common import sha256_file
src, out, hdr = sys.argv[1:4]
lines = open(src).read().split('\n')
header = open(hdr).read().rstrip('\n').split('\n')
i = 0
while i < len(lines) and lines[i].startswith('#'):
    i += 1
body = lines[i:]
# drop comment-only lines inside the body that carry build-process remarks
body_out = [l for l in body if not l.lstrip().startswith('#')]
open(out, 'w').write('\n'.join(header + body_out))
def payload(ls):
    return [l for l in ls if l.strip() and not l.lstrip().startswith('#')]
a, b = payload(lines), payload(open(out).read().split('\n'))
same = a == b
print(f'PAYLOAD-IDENTITY {out.split("/")[-1]}: {"IDENTICAL" if same else "DIFFERENT"} '
      f'({len(a)} non-comment lines); in sha256 {sha256_file(src)[:16]} out sha256 {sha256_file(out)[:16]}')
sys.exit(0 if same else 1)
