#!/usr/bin/python3
# Update the autogenerated part of rust-X.Y-src.install.in, by including the vendored
# dependencies of the standard library.

import argparse
import os

parser = argparse.ArgumentParser()
parser.add_argument("vendor", help="path to vendor directory of standard library dependencies")
args = parser.parse_args()

install_path = "debian/rust-X.Y-src.install.in"
install_list = []

for x in os.listdir(args.vendor):
    install_list.append(f"vendor/{x}" + " usr/src/rustc-${env:RUST_LONG_VERSION}" + f"/vendor")

# Read the existing file
with open(install_path, "r") as f:
    lines = f.readlines()

start_marker = "# Do not edit: AUTOGENERATED"
end_marker = "# AUTOGENERATED END"

start_idx = None
end_idx = None

for i, line in enumerate(lines):
    if start_marker in line:
        start_idx = i
    if end_marker in line:
        end_idx = i
        break

if start_idx is not None and end_idx is not None and start_idx < end_idx:
    new_lines = (
        lines[:start_idx + 1]
        + [line + "\n" for line in install_list]
        + lines[end_idx:]
    )
    with open(install_path, "w") as f:
        f.writelines(new_lines)
else:
    raise RuntimeError(f"Could not find AUTOGENERATED markers in {install_path}")

# print(args.vendor)