#!/usr/bin/python3

# Copyright (C) 2013, Daniel Narvaez
#
# 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 St, Fifth Floor, Boston, MA  02110-1301  USA

import os
import subprocess
import signal
import sys
import shlex

import gi
gi.require_version('SugarRunner', '1.0')
from gi.repository import SugarRunner

devnull = open("/dev/null")


def _setup_outputs():
    """Sugar doesn't handle multiple outputs properly. To avoid issues
       we use the first output in the list returned by xrandr and turn
       off everything else.
    """
    outputs = SugarRunner.list_outputs()
    if not outputs:
        return

    on_output = os.environ.get("SUGAR_RUNNER_OUTPUT", outputs[0])
    for output in outputs:
        if output != on_output:
            subprocess.check_call(["xrandr", "--output", output, "--off"])


def _load_xkb_config():
    if "SUGAR_RUNNER_XKBCONFIG" not in os.environ:
        return

    with open(os.environ["SUGAR_RUNNER_XKBCONFIG"], 'rb') as f:
        config = f.read()

    process = subprocess.Popen(["xkbcomp", "-", os.environ["DISPLAY"]],
                               stdin=subprocess.PIPE, stdout=devnull)
    process.communicate(input=config)


def _add_output_to_environ(output):
    for line in output.strip().split("\n"):
        splitted = line.strip().split("=", 1)
        if len(splitted) == 2:
            os.environ[splitted[0]] = splitted[1]


def _start_dbus():
    output = subprocess.check_output(["dbus-launch", "--exit-with-session"])
    _add_output_to_environ(output.decode())


def _start_keyring():
    output = subprocess.check_output(["gnome-keyring-daemon",
                                      "--start", "-d",
                                      "--components=secrets,pkcs11,ssh,gpg"])
    _add_output_to_environ(output.decode())


def _setup_xdg_user_dirs():
    subprocess.check_call("xdg-user-dirs-update")


_setup_outputs()
_setup_xdg_user_dirs()
_load_xkb_config()
_start_dbus()
_start_keyring()

if subprocess.call(["sugar"]) != 0:
    os.kill(int(os.environ["SUGAR_RUNNER_PID"]), signal.SIGUSR1)

if 'GNOME_KEYRING_PID' in os.environ:
    os.kill(int(os.environ["GNOME_KEYRING_PID"]), signal.SIGTERM)
