#!/bin/sh

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 /var/lib/lxc/${_CONTAINER}/config ]; then
	echo "E: $(basename ${0}): /var/lib/lxc/${_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' /var/lib/lxc/${_CONTAINER}/config
echo "lxc.aa_profile = ${profile}" >> /var/lib/lxc/${_CONTAINER}/config

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

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