#!/bin/sh
# -*- coding: utf-8 -*-

# Copyright (C) 2014 Canonical Ltd.
# Author: Stéphane Graber <stgraber@ubuntu.com>

# 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; version 3 of the License.
#
# 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, see <http://www.gnu.org/licenses/>.

set -e

# Kill the unity_system_compistor in the container as well as killing this
# script.
kill_unity_system_compositor()
{
  CHILD_PID=`ps -e -o pid= -o ppid= | awk -v pid="$PARENT_PID" '$2 == pid {print $1}'`
  kill $CHILD_PID
  wait $PARENT_PID
  exit 0
}

CONTAINER_NAME="unity8-lxc"

[ -e "/var/lib/lxc/$CONTAINER_NAME/config" ] || \
    (echo "Container doesn't exist" && exit 1)

trap kill_unity_system_compositor TERM EXIT

lxc-wait -t 0 -s RUNNING -n $CONTAINER_NAME || lxc-start -n $CONTAINER_NAME -d && \
  lxc-wait -t 5 -s RUNNING -n $CONTAINER_NAME && sleep 0.5

lxc-attach -n $CONTAINER_NAME -- /usr/sbin/unity-system-compositor.sleep $* &

PARENT_PID=$!

# Just wait until we get a signal from lightdm to stop.
wait $PARENT_PID
