#!/usr/bin/env python3
######## Imports ########
#### Standard Library ####
import argparse
import subprocess
import shutil
import os
import sys
from pathlib import Path

######## Arguments ########
# Define parser object
parser = argparse.ArgumentParser()
# Add arguments
parser.add_argument('--manifest-path', required=True)
parser.add_argument('--output', required=True)
parser.add_argument('--lib-name', required=True)
# Collect arguments
args = parser.parse_args()

######## Execution ########
env = os.environ.copy()
if sys.platform == "darwin":
    current_flags = env.get("RUSTFLAGS", "")
    macos_flags = "-C link-arg=-undefined -C link-arg=dynamic_lookup"
    env["RUSTFLAGS"] = f"{current_flags} {macos_flags}"

# Check that Cargo.toml file is valid
subprocess.check_call(
    ['cargo', 'metadata', '--no-deps', '--manifest-path', args.manifest_path],
    stdout=subprocess.DEVNULL,
)

# compile rust project
subprocess.check_call(
    [
        'cargo', 'build',
        '--release',
        '--manifest-path', args.manifest_path,
    ],
    env=env,
)

manifest_dir = Path(args.manifest_path).parent
target_dir = manifest_dir / 'target' / 'release'
crate_name = manifest_dir.name
cargo_prefix = f"lib{crate_name}"

# Platform dependent, but PyO3 naming is consistent
for file in target_dir.iterdir():
    if crate_name in file.name and file.suffix in ('.so', '.dylib', '.pyd'):
        shutil.copy(file, args.output)
        break
else:
    raise RuntimeError("Built library not found")


