#!/usr/bin/python3
"""
Enable osbuild Boot Test service

Creates a Boot Test service that executes the given `script` (sending output to
/dev/vport0p1) then immediately shuts down the system.

Creates `/etc/systemd/system/osbuild-test.service`, and a symlink to it in
`/etc/systemd/system/multi-user.target.wants/`.
"""


import os
import sys

import osbuild.api


SCHEMA = """
"additionalProperties": false,
"required": ["script"],
"properties": {
  "script": {
    "type": "string",
    "description": "Full path to a script that verifies successful bootup"
  }
}
"""


def main(tree, options):
    script = options["script"]

    unit = f"""
[Unit]
Description=Boot Test
Wants=dev-vport0p1.device
After=dev-vport0p1.device

[Service]
StandardOutput=file:/dev/vport0p1
ExecStart={script}
ExecStopPost=/usr/bin/systemctl poweroff
"""
    with open(f"{tree}/etc/systemd/system/osbuild-test.service", "w") as f:
        f.write(unit)

    os.symlink("../osbuild-test.service",
               f"{tree}/etc/systemd/system/multi-user.target.wants/osbuild-test.service")

    return 0


if __name__ == '__main__':
    args = osbuild.api.arguments()
    r = main(args["tree"], args["options"])
    sys.exit(r)
