#!/bin/sh
# Version: 2018-06-07

CONTAINER=mygui
STARTED=false
rootpath=/home/USERNAME/MYPROJECTS

if [ "$#" -lt 1 ]; then
    echo 'No command given.'
    exit
fi

# Create cd command if we are in the shared folder.
relpath="${PWD#$rootpath}"
if [ "${relpath}" != "${PWD}" ]; then
    cdcmd="cd /home/ubuntu/mnt/${relpath#/} && "
else
    cdcmd=""
fi

if ! lxc-wait -n $CONTAINER -s RUNNING -t 0; then
    lxc-start -n $CONTAINER -d
    lxc-wait -n $CONTAINER -s RUNNING
    STARTED=true
fi

# Run as root if using lrs command.
if [ "${0##*/}" = 'lrs' ]; then
    lxc-attach --clear-env --keep-var DISPLAY -n $CONTAINER -- su -c "${cdcmd}$*"
else
    lxc-attach --clear-env --keep-var DISPLAY -n $CONTAINER -- su - ubuntu -c "${cdcmd}$*"
fi

if [ "$STARTED" = "true" ]; then
    lxc-stop -n $CONTAINER -t 10
fi
