#!/usr/bin/env python3
"""Start a newly built native OS image on the configured managed network."""
import sys
import mykos_vm as vm
from mykos_runtime import config, run, PODMAN, NATIVE_OS_NAMES
from mykos_network import native_arguments as arguments


def start(os_name):
    if os_name not in NATIVE_OS_NAMES:
        raise ValueError('Select a supported native Linux image')
    with vm.locked():return launch(os_name)


def launch(os_name):
    if os_name not in NATIVE_OS_NAMES:raise ValueError('Select a supported native Linux image')
    args = arguments(config(), os_name)
    return run([PODMAN,'run','-d','-it','--hostname',os_name,'--name',os_name,
                '--rm','--privileged','--volume','/sys/fs/cgroup:/sys/fs/cgroup:ro','--memory=4g','--pull=never',*args,os_name,'/sbin/init'])


if __name__ == '__main__':
    if len(sys.argv) != 2: raise SystemExit('Usage: mykos-native-image-start OS')
    try: print(start(sys.argv[1]))
    except (ValueError, RuntimeError, OSError) as error: raise SystemExit(str(error))
