#!/bin/sh

# (C) Copyright Canonical 2011,2012

# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.

# This library 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
# Lesser General Public License for more details.

# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

. /usr/share/lxc/lxc.functions

set -e

_OPTIONS="$(getopt -o n: -l name: -- "${@}")"

if [ "${?}" -ne 0 ]
then
	echo "Usage: $(basename ${0}) -n|--name CONTAINER" >&2
	echo "  creates a custom profile (copied from the default) for CONTAINER"
	exit 1
fi

eval set -- "${_OPTIONS}"

while true
do
	case "${1}" in
		-n|--name)
			_CONTAINER="${2}"
			shift 2
			;;

		--)
			shift
			break
			;;

		*)
			echo "E: $(basename ${0}): internal error ${0}" >&2
			exit 1
			;;
	esac
done

if [ `id -u` -ne 0 ]; then
	echo "E: $(basename ${0}): must run with privilege"
	exit 1
fi

if [ -z "${_CONTAINER}" ]
then
	echo "E: $(basename ${0}): missing container name, use --name option" >&2
	exit 1
fi

if [ ! -f $lxc_path/${_CONTAINER}/config ]; then
	echo "E: $(basename ${0}): $lxc_path/${_CONTAINER}/config - no such file"
	exit 1
fi

profile="lxc-${_CONTAINER}"
if [ -f /etc/apparmor.d/lxc/${profile} ]; then
	echo "E: $(basename ${0}): custom profile already exists"
	exit 1
fi

if [ ! -f /etc/apparmor.d/lxc/lxc-default ]; then
	echo "E: $(basename ${0}): default profile does not exist!"
	exit 1
fi

cp -f /etc/apparmor.d/lxc/lxc-default /etc/apparmor.d/lxc/${profile}
sed -i "s/profile lxc-container-default/profile ${profile}/" /etc/apparmor.d/lxc/${profile}

sed -i '/lxc.aa_profile/d' $lxc_path/${_CONTAINER}/config
echo "lxc.aa_profile = ${profile}" >> $lxc_path/${_CONTAINER}/config

/lib/init/apparmor-profile-load lxc-containers

echo "Profile for ${_CONTAINER} updated.  Edit /etc/apparmor.d/lxc/${profile} to customize."
