#!/usr/bin/env python3
# Copyright 2019-2020 Collabora, Ltd
# SPDX-License-Identifier: BSL-1.0
# Author: Ryan Pavlik <ryan.pavlik@collabora.com>
"""XR Hardware generation helper code."""

# pylint: disable=E501
_SHARED_PREFIX = """# Do not edit this file - generated by {script}
# SPDX-License-Identifier: BSL-1.0
"""


_RULES_TEMPLATE_PREFIX = """
# Must be located at a number smaller than 73 for uaccess to work right!

# Skip if a remove
ACTION=="remove", GOTO="xrhardware_end"

"""

# Must be before 73 to have uaccess do what it should!
_RULES_TEMPLATE_SUFFIX = """

# Exit if we didn't find one
ENV{ID_xrhardware}!="1", GOTO="xrhardware_end"

# XR devices with serial ports aren't modems, modem-manager
ENV{ID_xrhardware_USBSERIAL_NAME}!="", SUBSYSTEM=="usb", ENV{ID_MM_DEVICE_IGNORE}="1"

# Make friendly symlinks for XR USB-Serial devices.
ENV{ID_xrhardware_USBSERIAL_NAME}!="", SUBSYSTEM=="tty", SYMLINK+="ttyUSB.$env{ID_xrhardware_USBSERIAL_NAME}"

LABEL="xrhardware_end"
"""  # noqa: E501 # it's too long because that's what the template is.


def generate_file_contents(script, body):
    """Return generated file contents for the given script file and body."""
    from pathlib import Path
    script = str(Path(script).name)
    shared_prefix = _SHARED_PREFIX.format(script=script)
    return '\n'.join((shared_prefix, body))


def generate_rules_file_contents(script, fn, body):
    """Return the body surrounded by the rules template."""
    parts = ['# ' + fn, _RULES_TEMPLATE_PREFIX, body, _RULES_TEMPLATE_SUFFIX]
    return generate_file_contents(script, "\n".join(parts))
