#!/bin/bash
# -*- coding: utf-8 -*-
#
# Copyright (C) 2018-2021 Linaro Limited
#
# Author: Senthil Kumaran S <senthil.kumaran@linaro.org>
#
# This file is part of LAVA LXC mocker.
#
# Released under the MIT License:
# http://www.opensource.org/licenses/mit-license.php
#
# Mocks lxc-create command which is used by LAVA.

# Get the list of requested packages.
PACKAGES=$(sed 's/,/ /g' <<< $(cut -d' ' -f1 <<< $(awk -F'--packages ' '{print $2}' <<< "$@")))

while getopts "qt:n:" opt; do
    case $opt in
        q)
            QUIET=1
            ;;
        t)
            TEMPLATE="$OPTARG"
            ;;
        n)
            LXC_NAME="$OPTARG"
            ;;
        *)
            ;;
    esac
done

if [ "$PACKAGES" ] && [ "$QUIET" ]; then
    DEBIAN_FRONTEND=noninteractive apt-get -q update > /dev/null 2>&1
    # install the requested packages.
    DEBIAN_FRONTEND=noninteractive apt-get -q install -y $PACKAGES > /dev/null 2>&1
elif [ "$PACKAGES" ]; then
    DEBIAN_FRONTEND=noninteractive apt-get -q update
    # install the requested packages.
    DEBIAN_FRONTEND=noninteractive apt-get -q install -y $PACKAGES
fi

if [ "$LXC_NAME" ]; then
    # create dummy lxc rootfs.
    if [ "$LXC_MOCKER_USE_OVERLAY" ]; then
        mkdir -p /var/lib/lxc/${LXC_NAME}/{rootfs,upperdir,workdir}

        mount -t overlay overlay -o lowerdir=/,upperdir=/var/lib/lxc/${LXC_NAME}/upperdir,workdir=/var/lib/lxc/${LXC_NAME}/workdir /var/lib/lxc/${LXC_NAME}/rootfs
        mount -t proc /proc /var/lib/lxc/${LXC_NAME}/rootfs/proc
        mount --rbind /sys /var/lib/lxc/${LXC_NAME}/rootfs/sys
        mount --rbind /dev /var/lib/lxc/${LXC_NAME}/rootfs/dev

	cp /etc/resolv.conf /var/lib/lxc/${LXC_NAME}/rootfs/etc/resolv.conf
	cp /etc/hosts /var/lib/lxc/${LXC_NAME}/rootfs/etc/hosts
    else
        mkdir -p /var/lib/lxc/${LXC_NAME}
        ln -s / /var/lib/lxc/${LXC_NAME}/rootfs
    fi
fi
