#!/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 an X client in a dedicated Xwayland server """

import os
import sys
from wlheadless.xwayland import Xwayland


def print_usage(argv0 = ''):
    """ Shows usage """
    print('usage: %s <Xwayland arguments> -- xclient <X client arguments>\n' % argv0)
    print('Run an X client in a dedicated Xwayland server.\n')
    sys.exit(os.EX_USAGE)


def parse_args(args = None):
    """ Simple home-brewed arguments parser """
    xwayland_args = []
    command_args = []
    separator = '--'
    after_separator = False
    for argument in args:
        if not after_separator and argument == separator:
            after_separator = True;
        else:
            if after_separator:
                command_args.append(argument)
            else:
                xwayland_args.append(argument)
    return (xwayland_args, command_args)


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

xwayland = Xwayland()
xwayland.setup_tempdir()
xwayland.setup_xauth()

xserver_args = ['-auth', xwayland.xauthfile]
xserver_args.extend(xwayland_args)

if xwayland.spawn_xwayland(xserver_args) < 0:
    xwayland.cleanup()
    sys.exit(status)

if xwayland.create_xauth_entry() != 0:
    xwayland.cleanup()
    sys.exit(status)

try:
    status = xwayland.run_command(command_args)
except Exception as error:
    print(str(error))

xwayland.cleanup()
sys.exit(status)
