#!/bin/sh
# ------------------------------------------------------------------
#
#    Copyright (C) 2013 Canonical Ltd.
#
#    This program is free software; you can redistribute it and/or
#    modify it under the terms of version 2 of the GNU General Public
#    License published by the Free Software Foundation.
#
# ------------------------------------------------------------------

set -e

# Wrapper around aa-exec to set various click variables:
# https://wiki.ubuntu.com/SecurityTeam/Specifications/ApplicationConfinement#Launching_applications

usage() {
    echo "`basename $0` -p <profile> <args to aa-exec> -- <command> <arg1> ..."
}

profile=""
while getopts hp: f ; do
    case "$f" in
        p) profile="$OPTARG";;
        h) usage; exit 0;;
        *) usage; exit 1;;
    esac
done

if [ -z "$profile" ]; then
    usage
    exit 1
fi

pkgname=`echo "$profile" | cut -d '_' -f 1`

# Make sure we have sane defaults based on the XDG spec
if [ -z "$XDG_CACHE_HOME" ]; then
    export XDG_CACHE_HOME="$HOME/.cache"
fi
if [ -z "$XDG_CONFIG_HOME" ]; then
    export XDG_CONFIG_HOME="$HOME/.config"
fi
if [ -z "$XDG_DATA_HOME" ]; then
    export XDG_DATA_HOME="$HOME/.local/share"
fi
if [ -z "$XDG_RUNTIME_DIR" ]; then
    export XDG_RUNTIME_DIR="/run/user/$(id -ru)" # Ubuntu-specific
fi

# This may be useful to apps
export APP_ID="$profile"

# Set application isolation environment
export UBUNTU_APPLICATION_ISOLATION=1
export TMPDIR="$XDG_RUNTIME_DIR/confined/$pkgname"
mkdir -p "$TMPDIR" || true
export __GL_SHADER_DISK_CACHE_PATH="$XDG_CACHE_HOME/$pkgname"

aa_exec="aa-exec"
if ! which $aa_exec >/dev/null ; then
    aa_exec="/usr/sbin/aa-exec"
fi
exec $aa_exec "$@"
