#!/usr/bin/env python3
"""Create lab-only credentials without replacing existing configuration."""

import argparse
import os
import secrets
import string
import tempfile
from pathlib import Path

ROOT = Path(__file__).resolve().parent
ENV_FILE = ROOT / '.env'
ALPHABET = string.ascii_letters + string.digits


def token(length):
    return ''.join(secrets.choice(ALPHABET) for _ in range(length))


def create_env():
    values = {
        'MISP_HTTP_PORT': '18081',
        'ADMIN_EMAIL': 'admin@sectools-lab.test',
        'ADMIN_ORG': 'SecTools Lab',
        'ADMIN_PASSWORD': token(24) + 'a9Z!',
        'ADMIN_KEY': token(40),
        'ENCRYPTION_KEY': token(32),
        'GPG_PASSPHRASE': token(32),
        'MYSQL_PASSWORD': token(32),
        'MYSQL_ROOT_PASSWORD': token(32),
        'REDIS_PASSWORD': token(32),
        'SUPERVISOR_PASSWORD': token(32),
    }
    # Publish the complete file atomically, without replacing an existing file.
    fd, temporary = tempfile.mkstemp(prefix='.env.', dir=ROOT, text=True)
    try:
        with os.fdopen(fd, 'w') as file:
            file.write('\n'.join(f'{key}={value}' for key, value in values.items()) + '\n')
        try:
            os.link(temporary, ENV_FILE)
        except FileExistsError:
            return False
        return True
    finally:
        Path(temporary).unlink()


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--keep-existing', action='store_true', help='Continue successfully if an environment file already exists.')
    args = parser.parse_args()
    if create_env():
        print('Created lab/.env with unique credentials. Values are not printed.')
    elif args.keep_existing:
        print('Reusing lab/.env.')
    else:
        raise SystemExit('.env already exists; kept unchanged.')


if __name__ == '__main__':
    main()
