#!/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

CONTAINER_NAME="unity8-lxc"

export DESKTOP_SESSION=unity8-mir

ROOTFS=$(lxc-info -c lxc.rootfs -n $CONTAINER_NAME -H)
RUNPATH="/proc/$(lxc-info -p -n $CONTAINER_NAME -H)/root"

# Add the user and the primary group
if ! lxc-attach -n $CONTAINER_NAME -- getent passwd $SUDO_UID; then
    getent passwd $SUDO_UID >> $RUNPATH/etc/passwd
fi

if ! lxc-attach -n $CONTAINER_NAME -- getent group $SUDO_GID; then
    getent group $SUDO_GID >> $RUNPATH/etc/group
fi

# Create the XDG path
mkdir -p $RUNPATH/run/user/$SUDO_UID
chown -R $SUDO_UID:$SUDO_GID $RUNPATH/run/user/$SUDO_UID

# Start Unity8 using the Upstart script
# This also sets up the cgroups for the user
(cat << EOF
for cgroup in \$(cut -d: -f2 /proc/self/cgroup); do
  cgm create \$cgroup $SUDO_USER
  cgm chown \$cgroup $SUDO_USER $SUDO_UID $SUDO_GID
  cgm movepid \$cgroup $SUDO_USER \$\$
done

rm -Rf /run/systemd
cp -R /var/lib/host-systemd /run/systemd

if [ ! -L /dev/shm ] && [ -e /dev/shm ]; then
  rmdir /dev/shm 2>/dev/null || mv /dev/shm /dev/shm.bak
  ln -s /run/shm /dev/shm
fi

sudo -u $SUDO_USER -E /usr/bin/lightdm-unity8-session
EOF
) | lxc-attach -n $CONTAINER_NAME -- bash

# Tell logind to kill the user to clean up from logging out of the
# Unity 8 session inside the container.
loginctl kill-user $SUDO_USER
