#!/usr/bin/env bash
# Copyright 2016 Canonical Ltd.  This software is licensed under the
# GNU Affero General Public License version 3 (see the file LICENSE).

# Exit immediately if a command exits with a non-zero status.
set -o errexit
# Treat unset variables as an error when substituting.
set -o nounset


PROFILE=maas-dev-$USER

function error {
    echo "$@"
    exit 1
}

function check_exists {
    if ! type -p $1 &> /dev/null; then
        error "$1 is not installed. (sudo apt install $2)"
    fi
}

check_exists lxc lxd
check_exists bzr bzr
check_exists setfacl acl

cd "$(dirname $0)"/..
SANDBOX=$(pwd)
cd ..
SHARED_REPO=$(pwd)

if bzr info | grep -q ^Shared; then
    echo "Using shared repository for mount point:"
    echo "    $SHARED_REPO"
else
    echo "Warning: could not find a bzr shared repository at:"
    echo "    $SHARED_REPO"
fi

# Recreate the profile from scratch.
if lxc profile show $PROFILE &> /dev/null; then
    echo "LXD profile already exists: $PROFILE (skipping creation)"
    echo "If you want to recreate the profile, run:"
    echo "    lxc profile delete $PROFILE"
    echo "Then re-run this script."
else
    lxc profile copy default $PROFILE

    # Add a mount point from wherever the MAAS sandbox is to /opt/src/maas 
    # on the container.
    lxc profile device add $PROFILE maas-bindmount \
        disk source=$SHARED_REPO path=/opt/src/maas

    # Add a mount point to the user's eventual $HOME in the container.
    lxc profile device add $PROFILE home-bindmount \
        disk source=$HOME path=/home/$USER

    # Make sure the profile is set up with the appropriate permissions.
    lxc profile set $PROFILE raw.lxc \
        "lxc.aa_profile=unconfined
         lxc.cgroup.devices.allow = b 7:* rwm
         lxc.cgroup.devices.allow = c 10:237 rwm"
    lxc profile set $PROFILE security.privileged true
fi

##
## NOTE: This section is commented out because we are using priveleged
## containers. Leaving this in the script, in case we revisit that decision.

# In order to find the UID for the normal user inside the container, we need
# to consult the mapping in /etc/subuid to find out which UIDs have been
# allocated to LXD.
# LXD_UID_ZERO=$(awk -F: '/^lxd:/ { print $2 }' /etc/subuid)
# The first user created in the container will always have UID 1000, hence the
# need to add 1000.
# let LXD_USER_UID=$LXD_UID_ZERO+1000
# if [ $(getfacl . | grep $LXD_USER_UID | wc -l) -eq 2 ]; then
#     echo "Found existing ACL for UID: $LXD_USER_UID. (skipping setfacl)"
# else
#     echo "Exposing bind mounts to LXD containers requires special filesystem"
#     echo "permissions, since LXD cannot normally access files on the host."
#     echo "These permissions will now be applied to:"
#     echo "    $SHARED_REPO"
#     echo "Adding filesystem ACL for UID: $LXD_USER_UID (please wait)..."
#     setfacl -m default:user:$LXD_USER_UID:rwX -R $SHARED_REPO
#     setfacl -m user:$LXD_USER_UID:rwX -R $SHARED_REPO
# fi
