"""Creates vendor_secret.txt once (keep it forever, back it up) and writes build/QuickSoftPOS.py with that SECRET patched in."""
import os, re, secrets, sys
here = os.path.dirname(os.path.abspath(__file__))
sec_file = os.path.join(here, "vendor_secret.txt")
if not os.path.exists(sec_file):
    with open(sec_file, "w") as f:
        f.write(secrets.token_hex(24))
    print("New secret created in vendor_secret.txt - BACK IT UP. Losing it means old keys can no longer be checked.")
secret = open(sec_file).read().strip()
src = open(os.path.join(here, "QuickSoftPOS.py"), encoding="utf-8").read()
new, n = re.subn(r'^SECRET = b".*"$', 'SECRET = b"%s"' % secret, src, count=1, flags=re.M)
if n != 1:
    sys.exit("Could not find the SECRET line.")
os.makedirs(os.path.join(here, "build_src"), exist_ok=True)
for name in ("QuickSoftPOS.py",):
    open(os.path.join(here, "build_src", name), "w", encoding="utf-8").write(new)
import shutil
shutil.copy(os.path.join(here, "QuickSoftKeygen.py"), os.path.join(here, "build_src", "QuickSoftKeygen.py"))
print("Build sources ready with your private secret.")
