#!/usr/bin/env python3
"""Builder-Aufruf für eine geprüfte tbrt-Vorlage; keine Cross-Toolchain-Installation."""
import argparse
import os
from pathlib import Path
import shutil
import subprocess

TARGETS = ('x86_64-pc-windows-msvc', 'aarch64-apple-darwin',
           'x86_64-unknown-linux-gnu', 'aarch64-unknown-linux-gnu')


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--target', choices=TARGETS, required=True)
    parser.add_argument('--output', type=Path, required=True,
                        help='neues Verzeichnis für tbrt und tbrt.meta')
    args = parser.parse_args()
    output = args.output.resolve()
    root = Path(__file__).resolve().parents[2]
    if output.exists():
        parser.error(f'Ausgabeverzeichnis existiert bereits: {output}')
    subprocess.run(['cargo', 'build', '--locked', '--release', '--target', args.target,
                    '-p', 'tb-runner', '--bin', 'tbrt'], cwd=root, check=True)
    name = 'tbrt.exe' if args.target == TARGETS[0] else 'tbrt'
    target_dir = Path(os.environ.get('CARGO_TARGET_DIR', root / 'target'))
    if not target_dir.is_absolute():
        target_dir = root / target_dir
    output.mkdir(parents=True)
    try:
        shutil.copy2(target_dir / args.target / 'release' / name, output / name)
        subprocess.run(['cargo', 'run', '--locked', '--release', '-p', 'tb-export',
                        '--bin', 'tb-template', '--', str(output / name), args.target],
                       cwd=root, check=True)
    except BaseException:
        shutil.rmtree(output)
        raise
    print(output)


if __name__ == '__main__':
    main()
