#!/bin/bash

# This is a modified version of /usr/share/lxc/templates/lxc-openmandriva
# that comes with OpenMandriva changed to suit vagrant-lxc needs

#
# template script for generating openmandriva container for LXC
#

#
# lxc: linux Container library

# Authors:
# Alexander Khryukin <alexander@mezon.ru>
# Vokhmin Alexey V   <avokhmin@gmail.com>

# 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA


set -e

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

extract_rootfs()
{
    tarball=$1
    arch=$2
    rootfs=$3

    echo "Extracting $tarball ..."
    mkdir -p $(dirname $rootfs)
    (cd `dirname $rootfs` && tar xfz $tarball)
    return 0
}

install_openmandriva()
{
    rootfs=$1
    release=$2
    tarball=$3
    mkdir -p /var/lock/subsys/

    (
        flock -x 200
        if [ $? -ne 0 ]; then
            echo "Cache repository is busy."
            return 1
        fi

        extract_rootfs $tarball $arch $rootfs
        if [ $? -ne 0 ]; then
            echo "Failed to copy rootfs"
            return 1
        fi

        return 0

    ) 200>/var/lock/subsys/lxc

    return $?
}

copy_configuration()
{
    path=$1
    rootfs=$2
    name=$3

    grep -q "^lxc.rootfs" $path/config 2>/dev/null || echo "lxc.rootfs = $rootfs" >> $path/config

    # if there is exactly one veth network entry, make sure it has an
    # associated hwaddr.
    nics=`grep -e '^lxc\.network\.type[ \t]*=[ \t]*veth' $path/config | wc -l`
    if [ $nics -eq 1 ]; then
        grep -q "^lxc.network.hwaddr" $path/config || sed -i -e "/^lxc\.network\.type[ \t]*=[ \t]*veth/a lxc.network.hwaddr = 00:16:3e:$(openssl rand -hex 3| sed 's/\(..\)/\1:/g; s/.$//')" $path/config
    fi

    if [ $? -ne 0 ]; then
        echo "Failed to add configuration"
        return 1
    fi

    return 0
}

post_process()
{
    rootfs=$1

    # rmdir /dev/shm for containers that have /run/shm
    # I'm afraid of doing rm -rf $rootfs/dev/shm, in case it did
    # get bind mounted to the host's /run/shm.  So try to rmdir
    # it, and in case that fails move it out of the way.
    if [ ! -L $rootfs/dev/shm ] && [ -d $rootfs/run/shm ] && [ -e $rootfs/dev/shm ]; then
        mv $rootfs/dev/shm $rootfs/dev/shm.bak
        ln -s /run/shm $rootfs/dev/shm
    fi
}

usage()
{
    cat <<EOF
usage:
    $1 -n|--name=<container_name>
        [-p|--path=<path>] [-c|--clean] [-R|--release=<openmandriva2013.0/rosa2012.1/cooker/ release>]
        [-4|--ipv4=<ipv4 address>] [-6|--ipv6=<ipv6 address>]
        [-g|--gw=<gw address>] [-d|--dns=<dns address>]
        [-P|--profile=<name of the profile>] [--rootfs=<path>]
        [-A|--arch=<arch of the container>]
        [-T|--tarball <tarball path>]
        [-S|--auth-key <auth-key path>]
        [-h|--help]
Mandatory args:
  -n,--name         container name, used to as an identifier for that container from now on
Optional args:
  -p,--path         path to where the container rootfs will be created, defaults to /var/lib/lxc. The container config will go under /var/lib/lxc in that case
  -c,--clean        clean the cache
  -R,--release      openmandriva2013.0/cooker/rosa2012.1 release for the new container. if the host is OpenMandriva, then it will default to the host's release.
  -4,--ipv4         specify the ipv4 address to assign to the virtualized interface, eg. 192.168.1.123/24
  -6,--ipv6         specify the ipv6 address to assign to the virtualized interface, eg. 2003:db8:1:0:214:1234:fe0b:3596/64
  -g,--gw           specify the default gw, eg. 192.168.1.1
  -G,--gw6          specify the default gw, eg. 2003:db8:1:0:214:1234:fe0b:3596
  -d,--dns          specify the DNS server, eg. 192.168.1.2
  -P,--profile      Profile name is the file name in /etc/lxc/profiles contained packages name for install to cache.
  -A,--arch         Define what arch the container will be [i586,x86_64,armv7l,armv7hl]
  ---rootfs         rootfs path
  -h,--help         print this help
EOF
    return 0
}

options=$(getopt -o hp:n:P:cR:4:6:g:d:A:S:T: -l help,rootfs:,path:,name:,profile:,clean:,release:,ipv4:,ipv6:,gw:,dns:,arch:,auth-key:,tarball: -- "$@")
if [ $? -ne 0 ]; then
    usage $(basename $0)
    exit 1
fi
eval set -- "$options"

# doesn't use
release=${release:-"cooker"} 

hostarch=$(uname -m)
while true
do
    case "$1" in
        -h|--help)      usage $0 && exit 0;;
        -p|--path)      path=$2; shift 2;;
        --rootfs)       rootfs_path=$2; shift 2;;
        -n|--name)      name=$2; shift 2;;
        -P|--profile)   profile=$2; shift 2;;
        -c|--clean)     clean=$2; shift 2;;
        -R|--release)   release=$2; shift 2;;
        -T|--tarball)   tarball=$2; shift 2;;
        -S|--auth-key)  auth_key=$2; shift 2;;
        -A|--arch)      arch=$2; shift 2;;
        -4|--ipv4)      ipv4=$2; shift 2;;
        -6|--ipv6)      ipv6=$2; shift 2;;
        -g|--gw)        gw=$2; shift 2;;
        -d|--dns)       dns=$2; shift 2;;
        --)             shift 1; break ;;
        *)              break ;;
    esac
done

arch=${arch:-$hostarch}
if [ $hostarch = "i586" -a $arch = "x86_64" ]; then
    echo "can't create x86_64 container on i586"
    exit 1
fi

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

if [ "$(id -u)" != "0" ]; then
    echo "This script should be run as 'root'"
    exit 1
fi

# detect rootfs
config="$path/config"
# if $rootfs exists here, it was passed in with --rootfs
if [ -z "$rootfs" ]; then
    if grep -q '^lxc.rootfs' $config 2>/dev/null ; then
        rootfs=`grep 'lxc.rootfs =' $config | awk -F= '{ print $2 }'`
    else
        rootfs=$path/rootfs
    fi
fi

install_openmandriva $rootfs $release $tarball
if [ $? -ne 0 ]; then
    echo "failed to install openmandriva $release"
    exit 1
fi

copy_configuration $path $rootfs $name $arch
if [ $? -ne 0 ]; then
    echo "failed write configuration file"
    exit 1
fi

post_process $rootfs $release

echo ""
echo "##"
echo "# The default user is 'vagrant' with password 'vagrant'!"
echo "# Use the 'sudo' command to run tasks as root in the container."
echo "##"
echo ""