#!/usr/bin/env python3
"""Import a private standalone catalog into a NEW private destination directory.

User choice happens before this tool. Never merge or overwrite an existing
catalog automatically. Credential contents are processed without being printed.
"""
import argparse
import json
import os
from pathlib import Path
import shutil

from private_bundle import private_directory, verified_members


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--destination', type=Path, required=True)
    args = parser.parse_args()
    os.umask(0o077)
    root = Path(__file__).resolve().parents[1]
    entries = verified_members(root)
    setup = json.loads(entries['PRIVATE_SETUP.json'])
    if setup['prepared_mode'] != 'standalone':
        raise ValueError('this bundle does not contain a standalone catalog')
    target = args.destination.absolute()
    if target.exists():
        raise ValueError('destination already exists; select a new private directory and preserve the existing catalog')
    private_directory(target)
    try:
        for name, data in entries.items():
            if name.startswith('private/keys/'):
                file = target / name.removeprefix('private/')
                file.parent.mkdir(mode=0o700, exist_ok=True)
                file.write_bytes(data)
                if os.name != 'nt':
                    file.chmod(0o600)
        catalog = entries['private/ssh-config.toml'].decode()
        # Forward slashes work in Windows TOML paths and need no backslash
        # escaping. Escape the replacement as TOML string content for quotes.
        replacement = json.dumps(target.as_posix(), ensure_ascii=False)[1:-1]
        catalog = catalog.replace('__SSHMCP_PRIVATE_DIR__', replacement)
        (target / 'ssh-config.toml').write_text(catalog, encoding='utf-8')
        (target / 'standalone.env').write_text('', encoding='utf-8')
    except Exception:
        # This directory was created exclusively for this import; no preexisting
        # user files are removed on failure.
        shutil.rmtree(target)
        raise
    print(json.dumps({'success': True, 'catalog': str(target / 'ssh-config.toml'), 'env_file': str(target / 'standalone.env'), 'private_directory': str(target)}))


if __name__ == '__main__':
    main()
