#!/bin/bash

#
# lxc: linux Container library

# Authors:
# Daniel Lezcano <daniel.lezcano@free.fr>

# 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

#
# This script allows to set or remove the setuid execution bit on the lxc tools.
# When the capabilities are set, a non root user can manage the containers.
#

usage()
{
    echo "lxc-setuid [-d] : set or remove setuid on the lxc tools"
}

setuid()
{
    if [ "$1" = "-r" ]; then
	chmod -s $2
    else
	chmod +s $1
    fi
}

lxc_setuid()
{
    setuid /usr/bin/lxc-attach
    setuid /usr/bin/lxc-create
    setuid /usr/bin/lxc-execute
    setuid /usr/bin/lxc-start
    setuid /usr/bin/lxc-restart
    setuid /usr/bin/lxc-unshare
    setuid /usr/bin/lxc-netstat
    setuid /usr/bin/lxc-checkpoint
    setuid /usr/lib/lxc/lxc-init

    test -e /usr/var/lib/lxc || mkdir -p /usr/var/lib/lxc
    chmod 0777 /usr/var/lib/lxc
}

lxc_dropuid()
{
    setuid -r /usr/bin/lxc-attach
    setuid -r /usr/bin/lxc-create
    setuid -r /usr/bin/lxc-execute
    setuid -r /usr/bin/lxc-start
    setuid -r /usr/bin/lxc-restart
    setuid -r /usr/bin/lxc-unshare
    setuid -r /usr/bin/lxc-netstat
    setuid -r /usr/bin/lxc-checkpoint
    setuid -r /usr/lib/lxc/lxc-init

    chmod 0755 /usr/var/lib/lxc
}

if [ "$(id -u)" != "0" ]; then
    echo "You have to be root to run this script"
    exit 1
fi


if [ $? != 0 ]; then
    usage
    exit 1
fi

set -- $(getopt dh $*)

for i in $*; do
    case "$1" in
	-d)
	    LXC_DROP_CAPS="yes"
	    shift
	    ;;
	-h)
	    usage
	    exit 0
	    ;;
	--)
	    shift
	    break
	    ;;
	*)
	    usage
	    exit 1
	    ;;
    esac
done;

if [ -z "$LXC_DROP_CAPS" ]; then
    lxc_setuid
else
    lxc_dropuid
fi
