#!/usr/bin/env python3
# -*- python -*-
#
# Copyright © 2023 Red Hat, Inc
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.

""" Run a Wayland client on a compositor headless """

import os
from pkgutil import get_data
from signal import SIGTERM
import sys
from wlheadless.wlheadless_common import WlheadlessCommon


def print_usage(argv0 = ''):
    """ Shows usage """
    print('usage: %s [-c compositor] <compositor arguments> -- client <client arguments>\n' % argv0)
    print('Run a Wayland client in a dedicated headless compositor instance.\n')
    sys.exit(os.EX_USAGE)


def parse_args(args = None):
    """ Simple home-brewed arguments parser """
    compositor = None
    compositor_args = []
    command_args = []
    separator = '--'
    setcompositor = '-c'
    after_separator = False
    nargs = len(args)
    i = 0
    while i < nargs:
        argument = args[i]
        if not after_separator:
            if argument == separator:
                after_separator = True
            elif not compositor and argument == setcompositor:
                if i + 1 < nargs:
                    i += 1
                    compositor = args[i]
            else:
                compositor_args.append(argument)
        else:
            command_args.append(argument)
        i += 1
    return (compositor, compositor_args, command_args)


status = os.EX_DATAERR
(compositor, compositor_args, command_args) = parse_args(sys.argv[1:])
if not command_args:
    print_usage(sys.argv[0])

wlheadless_common = WlheadlessCommon()
if not compositor:
    compositor = wlheadless_common.get_compositor()

wlheadless = wlheadless_common.load_compositor(compositor)
if not wlheadless:
    wlheadless_common.cleanup()
    sys.exit(status)

if wlheadless.run_compositor(compositor_args) < 0:
    wlheadless_common.cleanup()
    sys.exit(status)

if wlheadless.wait_compositor() != 0:
    wlheadless_common.cleanup()
    sys.exit(status)

try:
    status = wlheadless.spawn_client(command_args)
except Exception as error:
    print(str(error))

wlheadless_common.cleanup()
sys.exit(status)
