#!/bin/bash

set -e

STATE_DIR="/var"
HOOK_DIR="/usr/share/lxc/hooks"
CLONE_HOOK_FN="$HOOK_DIR/ubuntu-cloud-prep"
LXC_TEMPLATE_CONFIG="/usr/share/lxc/config"

# Make sure the usual locations are in PATH
export PATH=$PATH:/usr/sbin:/usr/bin:/sbin:/bin

if [ -r /etc/default/lxc ]; then
    . /etc/default/lxc
fi

am_in_userns() {
    [ -e /proc/self/uid_map ] || { echo no; return; }
    [ "$(wc -l /proc/self/uid_map | awk '{ print $1 }')" -eq 1 ] || { echo yes; return; }
    line=$(awk '{ print $1 " " $2 " " $3 }' /proc/self/uid_map)
    [ "$line" = "0 0 4294967295" ] && { echo no; return; }
    echo yes
}

in_userns=0
[ $(am_in_userns) = "yes" ] && in_userns=1

usage()
{
    cat <<EOF
LXC Container configuration for Granite instances

Generic Options
[ --rootfs <path> ]: Path in which rootfs will be placed
[ -T | --tarball ]: Location of tarball
[ -d | --debug ]: Run with 'set -x' to debug errors

EOF
    return 0
}

#options=$(getopt -o -- "$@")
#if [ $? -ne 0 ]; then
#    usage $(basename $0)
#    exit 1
#fi
#eval set -- "$options"

mapped_uid=-1
mapped_gid=-1

debug=0
while true
do
	case "$1" in 
	-h|--help)         usage $0 && exit 0;;
    -p|--path)         path=$2; shift 2;;
	-n|--name)         name=$2; shift 2;;
    -T|--tarball)      tarball=$2; shift 2;;
    -d|--debug)        debug=1; shift 1;;
    --rootfs)          rootfs=$2; shift 2;;

    --mapped-uid)      mapped_uid=$2; shift 2;;
    --mapped-gid)      mapped_gid=$2; shift 2;;
    --)                shift 1; break ;;
        *)              break ;;
    esac
done

if [ -z "$path" ]; then
	echo "'path' parameter is required"
	exit 1
fi

# detect rootfs
config="$path/config"
if [ -z "$rootfs" ]; then
	if grep -q '^lxc.rootfs' $config 2>/dev/null ; then
        rootfs=$(awk -F= '/^lxc.rootfs =/{ print $2 }' $config)
	else
		rootfs=$path/rootfs
	fi
fi

do_extract_rootfs() {
	trap EXIT
	trap SIGHUP
	trap SIGINT
	trap SIGINT
	trap SIGTERM

	echo "Extracting container rootfs"
	mkdir -p $rootfs
    cd $rootfs
    if [ $in_userns -eq 1 ]; then
        tar --anchored --exclude="dev/*" --numeric-owner -xpzf "$cache/$filename"
        mkdir -p $rootfs/dev/pts/
	else
		tar --numeric-owner -xpzf "$cache/$filename"
	fi
}

if [ -n "$tarball" ]; then
	do_extract_rootfs
else:
	echo "Missing tarball"
	exit 1
fi

if [ $mapped_uid -ne -1 ]; then
    chown $mapped_uid $path/config
    chown -R $mapped_uid $STATE_DIR
    chown -R $mapped_uid $cache
fi
if [ $mapped_gid -ne -1 ]; then
    chgrp $mapped_gid $path/config
    chgrp -R $mapped_gid $STATE_DIR
    chgrp -R $mapped_gid $cache
fi

