#!/usr/bin/env python
# SPDX-License-Identifier: GPL-2.0-only
# This scripts use bitbake api, so it has to be under the GPL-2.0 license

"""
    devtool wrapper for the coreos-device script
"""

import subprocess

from devtool import setup_tinfoil, parse_recipe

class InvalidImage(Exception):
    pass

def swupdate_www_push(args, config, basepath, workspace):
    """
        devtool update-device command

        Use devtool library to get information about the image from the
        bitbake context, then call update_device()
    """
    # Only use inside a bitbake environment, we can import some more libs here
    
    image = args.imagename
    tinfoil = setup_tinfoil(basepath=basepath)

    rd = parse_recipe(config, tinfoil, image, True)
    if not rd:
        # Error already shown
        return 1
    
    if not bb.data.inherits_class('coreos-image', rd):
        raise InvalidImage("Image should be based on the coreos-image class")

    if rd.getVar('COREOS_IMAGE_GENERATE_SWU') != "1":
        raise InvalidImage("COREOS_IMAGE_GENERATE_SWU should be set to '1'")
    
    image_name = rd.getVar('IMAGE_LINK_NAME')
    outputdir = rd.getVar('DEPLOY_DIR_IMAGE')

    return run(["coreos-device", "swupdate-www-push", f"{outputdir}/{image_name}.swu", args.target, f"--port={args.port}"])


def register_commands(subparsers, context):
    """Register devtool subcommands from this plugin"""
    subparsers.add_subparser_group('swupdate', 'Updating device using swupdate')
    cmd_push = subparsers.add_parser('swupdate-www-push', help='Update device with image',
                                       description='Deploy an image to a device using swupdate',
                                       group='swupdate')
    cmd_push.add_argument('imagename', help='Image recipe to deploy')
    cmd_push.add_argument('target', help='IP address of the running target')
    cmd_push.add_argument('-P', '--port', default=8080, help='Specify port to use for connection to the target')
    cmd_push.set_defaults(func=swupdate_www_push, fixed_setup=context.fixed_setup)

def run(cmd):
    return subprocess.run(cmd).returncode
