#!/bin/bash

#
# template script for generating Vine Linux container for LXC
#   (based on altlinux/centos template script)
#

#
# lxc: linux Container library

# Authors:
# Daisuke SUZUKI <daisuke@vinelinux.org>

# 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

# Detect use under userns (unsupported)
for arg in "$@"; do
    [ "$arg" = "--" ] && break
    if [ "$arg" = "--mapped-uid" -o "$arg" = "--mapped-gid" ]; then
        echo "This template can't be used for unprivileged containers." 1>&2
        echo "You may want to try the \"download\" template instead." 1>&2
        exit 1
    fi
done

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

# Configurations
arch=$(uname -i)
cache_base=/var/cache/lxc/vinelinux
default_path=/var/lib/lxc
default_profile=default
profile_dir=/etc/lxc/profiles
root_password=vineroot
default_user=vine
default_user_password=vine123
lxc_network_type=veth
lxc_network_link=lxcbr0

# is this vinelinux?
[ -f /etc/vine-release ] && is_vinelinux=true

configure_vinelinux()
{
    # Set default localtime to the host localtime if not set...
    if [ -e /etc/localtime -a ! -e ${rootfs_path}/etc/localtime ]
    then
        # if /etc/localtime is a symlink, this should preserve it.
        cp -a /etc/localtime ${rootfs_path}/etc/localtime
    fi

    # create /lxcroot
    touch ${rootfs_path}/lxcroot

    # fix bxxxn damaged halt script.
    if [ -f ${rootfs_path}/etc/init.d/halt ]
    then
        sed -e '/hwclock/,$d' \
            < ${rootfs_path}/etc/init.d/halt \
            > ${rootfs_path}/etc/init.d/lxc-halt

        echo '$command -f' >> ${rootfs_path}/etc/init.d/lxc-halt
        chmod 755 ${rootfs_path}/etc/init.d/lxc-halt

        # Link them into the rc directories...
        (
             cd ${rootfs_path}/etc/rc.d/rc0.d
             ln -s ../init.d/lxc-halt S00lxc-halt
             cd ${rootfs_path}/etc/rc.d/rc6.d
             ln -s ../init.d/lxc-halt S00lxc-reboot
        )
    fi

    # configure the network using the dhcp
    cat <<EOF > ${rootfs_path}/etc/sysconfig/network-scripts/ifcfg-eth0
DEVICE=eth0
BOOTPROTO=dhcp
ONBOOT=yes
HOSTNAME=${UTSNAME}
NM_CONTROLLED=no
TYPE=Ethernet
MTU=${MTU}
DHCP_HOSTNAME=\`hostname\`
EOF

    # set the hostname
    cat <<EOF > ${rootfs_path}/etc/sysconfig/network
NETWORKING=yes
HOSTNAME=${UTSNAME}
EOF

    # set minimal hosts
    cat <<EOF > $rootfs_path/etc/hosts
127.0.0.1 localhost.localdomain localhost $name
EOF

    # set minimal fstab
    cat <<EOF > $rootfs_path/etc/fstab
/dev/root               /                       rootfs   defaults        0 0
EOF

    # create lxc compatibility init script
    cat <<EOF > $rootfs_path/etc/init/lxc-sysinit.conf
start on startup
env container

pre-start script
        if [ "x\$container" != "xlxc" -a "x\$container" != "xlibvirt" ]; then
                stop;
        fi

        rm -f /var/lock/subsys/*
        rm -f /var/run/*.pid
        [ -e /etc/mtab ] || ln -s /proc/mounts /etc/mtab
        mkdir -p /dev/shm
        mount -t tmpfs -o nosuid,nodev tmpfs /dev/shm

        initctl start tty TTY=console
        telinit 3
        exit 0
end script
EOF

    # Enable services
    for service in network random
    do
       chroot ${rootfs_path} chkconfig $service --list &>/dev/null && chroot ${rootfs_path} chkconfig $service on || true
    done

    dev_path="${rootfs_path}/dev"
    rm -rf ${dev_path}
    mkdir -p ${dev_path}
    mknod -m 666 ${dev_path}/null c 1 3
    mknod -m 666 ${dev_path}/zero c 1 5
    mknod -m 644 ${dev_path}/random c 1 8
    mknod -m 644 ${dev_path}/urandom c 1 9
    mkdir -m 755 ${dev_path}/pts
    mkdir -m 1777 ${dev_path}/shm
    mknod -m 666 ${dev_path}/tty c 5 0
    chown root:tty ${dev_path}/tty
    mknod -m 600 ${dev_path}/tty0 c 4 0
    mknod -m 600 ${dev_path}/tty1 c 4 1
    mknod -m 600 ${dev_path}/tty2 c 4 2
    mknod -m 600 ${dev_path}/tty3 c 4 3
    mknod -m 600 ${dev_path}/tty4 c 4 4
    mknod -m 600 ${dev_path}/console c 5 1
    mknod -m 666 ${dev_path}/full c 1 7
    mknod -m 600 ${dev_path}/initctl p
    mknod -m 666 ${dev_path}/ptmx c 5 2
    chown root:tty ${dev_path}/ptmx
    ln -s /proc/self/fd ${dev_path}/fd
    ln -s /proc/kcore ${dev_path}/core
    mkdir -m 755 ${dev_path}/mapper
    mknod -m 600 ${dev_path}/mapper/control c 10 236
    mkdir -m 755 ${dev_path}/net
    mknod -m 666 ${dev_path}/net/tun c 10 200

    # setup console and tty[1-4] for login. note that /dev/console and
    # /dev/tty[1-4] will be symlinks to the ptys /dev/lxc/console and
    # /dev/lxc/tty[1-4] so that package updates can overwrite the symlinks.
    # lxc will maintain these links and bind mount ptys over /dev/lxc/*
    # since lxc.devttydir is specified in the config.

    # allow root login on console, tty[1-4], and pts/0 for libvirt
    echo "# LXC (Linux Containers)" >>${rootfs_path}/etc/securetty
    echo "lxc/console"  >>${rootfs_path}/etc/securetty
    echo "lxc/tty1"     >>${rootfs_path}/etc/securetty
    echo "lxc/tty2"     >>${rootfs_path}/etc/securetty
    echo "lxc/tty3"     >>${rootfs_path}/etc/securetty
    echo "lxc/tty4"     >>${rootfs_path}/etc/securetty
    echo "# For libvirt/Virtual Machine Monitor" >>${rootfs_path}/etc/securetty
    echo "pts/0"        >>${rootfs_path}/etc/securetty

    # prevent mingetty from calling vhangup(2) since it fails with userns.
    # Same issue as oracle template: prevent mingetty from calling vhangup(2)
    # commit 2e83f7201c5d402478b9849f0a85c62d5b9f1589.
    sed -i 's|mingetty|mingetty --nohangup|' $rootfs_path/etc/init/tty.conf

    # set root password
    echo "Setting root password to $root_password"
    echo "root:$root_password" | chroot $rootfs_path chpasswd
    # store root password
    touch ${config_path}/tmp_root_pass
    chmod 600 ${config_path}/tmp_root_pass
    echo ${root_password} > ${config_path}/tmp_root_pass
    echo "Storing root password in '${config_path}/tmp_root_pass'"

    # create default user 'vine'
    echo "Create default user 'vine'"
    chroot ${rootfs_path} /usr/sbin/useradd -G wheel ${default_user}
    echo "Setting default user \'${default_user}\' password to $default_user_password"
    echo "${default_user}:${default_user_password}" | chroot $rootfs_path chpasswd
    # store default user password
    touch ${config_path}/tmp_user_pass
    chmod 600 ${config_path}/tmp_user_pass
    echo "username: ${default_user}" > ${config_path}/tmp_user_pass
    echo "password: ${default_user_password}" >> ${config_path}/tmp_user_pass
    echo "Storing default user infomation in '${config_path}/tmp_user_pass'"

    return 0
}

download_vinelinux()
{
    # Default configuration
    FETCH_URL="http://updates.vinelinux.org/apt"

    # create cache dir
    mkdir -p $cache
    
    # check target availability
    if ! (vbootstrap | grep -q "${release}_${arch}"); then
        echo "Specified release and/or arch is not supported, aborting."
	return 1
    fi
    if [ "$(uname -i)" == "i386" ] && [ "${arch}" == "x86_64" ]; then
        echo "x86_64 containers does not run on $(uname -i) host, aborting."
	return 1
    fi

    # download a mini vinelinux into a cache
    echo "Downloading vinelinux minimal ..."
    VBOOTSTRAP="vbootstrap ${release}_${arch} ${FETCH_URL} $cache/partial"

    $VBOOTSTRAP

    if [ $? -ne 0 ]; then
        echo "Failed to download the rootfs, aborting."
        return 1
    fi
    
    # install additional packages
    PKG_LIST0="openssh-server openssh-clients etcskel sudo net-tools"
    PKG_LIST="$(grep -hs '^[^#]' "$profile_dir/$profile")"
    # if no configuration file $profile -- fall back to default list of packages
    PKG_LIST="$PKG_LIST0 $PKG_LIST"
    chroot $cache/partial apt-get -y install $PKG_LIST

    if [ $? -ne 0 ]; then
        echo "Failed to install additional packages to the rootfs, aborting."
        return 1
    fi
    
    mv "$cache/partial" "$cache/rootfs"
    echo "Download complete."

    return 0
}

copy_vinelinux()
{

    # make a local copy of the minivinelinux
    echo -n "Copying rootfs to $rootfs_path ..."
    #cp -a $cache/rootfs-$arch $rootfs_path || return 1
    # i prefer rsync (no reason really)
    mkdir -p $rootfs_path
    rsync -Ha $cache/rootfs/ $rootfs_path/
    return 0
}

update_vinelinux()
{
    chroot $cache/rootfs apt-get update
    chroot $cache/rootfs apt-get -y dist-upgrade
}

install_vinelinux()
{
    mkdir -p /var/lock/subsys/
    (
        flock -x 9
        if [ $? -ne 0 ]; then
            echo "Cache repository is busy."
            return 1
        fi

        echo "Checking cache download in $cache/rootfs ... "
        if [ ! -e "$cache/rootfs" ]; then
            download_vinelinux
            if [ $? -ne 0 ]; then
                echo "Failed to download 'vinelinux base'"
                return 1
            fi
        else
            echo "Cache found. Updating..."
            update_vinelinux
            if [ $? -ne 0 ]; then
                echo "Failed to update 'vinelinux base', continuing with last known good cache"
            else
                echo "Update finished"
            fi
        fi

        echo "Copy $cache/rootfs to $rootfs_path ... "
        copy_vinelinux
        if [ $? -ne 0 ]; then
            echo "Failed to copy rootfs"
            return 1
        fi
        return 0
    ) 9>/var/lock/subsys/lxc-vinelinux

    return $?
}

copy_configuration()
{

    mkdir -p $config_path
    grep -q "^lxc.rootfs" $config_path/config 2>/dev/null || echo "lxc.rootfs = $rootfs_path" >> $config_path/config
    cat <<EOF >> $config_path/config
lxc.utsname = $name
lxc.tty = 4
lxc.pts = 1024
lxc.cap.drop = sys_module mac_admin mac_override sys_time
EOF

    if [ "$arch" == "i386" ] && [ "$(uname -i)" == "x86_64" ]; then
        cat <<EOF >> $config_path/config

# lxc container architecture
lxc.arch = x86
EOF

    fi

    cat <<EOF >> $config_path/config
# When using LXC with apparmor, uncomment the next line to run unconfined:
#lxc.aa_profile = unconfined

#networking
lxc.network.type = $lxc_network_type
lxc.network.flags = up
lxc.network.link = $lxc_network_link
lxc.network.name = veth0
lxc.network.mtu = 1500
EOF
    if [ ! -z ${ipv4} ]; then
        cat <<EOF >> $config_path/config
lxc.network.ipv4 = $ipv4
EOF
    fi
    if [ ! -z ${gw} ]; then
        cat <<EOF >> $config_path/config
lxc.network.ipv4.gateway = $gw
EOF
    fi
#if [ ! -z ${ipv6} ]; then
#    cat <<EOF >> $config_path/config
#lxc.network.ipv6 = $ipv6
#EOF
#fi
#if [ ! -z ${gw6} ]; then
#    cat <<EOF >> $config_path/config
#lxc.network.ipv6.gateway = $gw6
#EOF
#fi
    cat <<EOF >> $config_path/config
#cgroups
lxc.cgroup.devices.deny = a
# /dev/null and zero
lxc.cgroup.devices.allow = c 1:3 rwm
lxc.cgroup.devices.allow = c 1:5 rwm
# consoles
lxc.cgroup.devices.allow = c 5:1 rwm
lxc.cgroup.devices.allow = c 5:0 rwm
lxc.cgroup.devices.allow = c 4:0 rwm
lxc.cgroup.devices.allow = c 4:1 rwm
# /dev/{,u}random
lxc.cgroup.devices.allow = c 1:9 rwm
lxc.cgroup.devices.allow = c 1:8 rwm
lxc.cgroup.devices.allow = c 136:* rwm
lxc.cgroup.devices.allow = c 5:2 rwm
# rtc
lxc.cgroup.devices.allow = c 10:135 rwm

lxc.mount.auto = cgroup:mixed proc:mixed sys:mixed
EOF

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

    return 0
}

clean()
{

    if [ ! -e $cache ]; then
        exit 0
    fi

    # lock, so we won't purge while someone is creating a repository
    (
        flock -x 9
        if [ $? != 0 ]; then
            echo "Cache repository is busy."
            exit 1
        fi

        echo -n "Purging the download cache for Vine Linux $release..."
        rm --preserve-root --one-file-system -rf $cache && echo "Done." || exit 1
        exit 0
    ) 9>/var/lock/subsys/lxc-vinelinux
}

usage()
{
    cat <<EOF
usage:
    $1 -n|--name=<container_name>
        [-p|--path=<path>] [-c|--clean] [-R|--release=<Vine Linux release>]
        [-4|--ipv4=<ipv4 address>]
        [-g|--gw=<gw address>] [-d|--dns=<dns address>]
	[-u|--user=<user>] [--password=<password>]
        [-P|--profile=<name of the profile>] [--rootfs=<path>]
        [-A|--arch=<arch of the container>]
        [-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      Vine Linux release [VineSeed, 6] for the new container, defaults to VineSeed
  -4,--ipv4         specify the ipv4 address to assign to the virtualized interface, eg. 192.168.1.123/24
  -g,--gw           specify the default gw, eg. 192.168.1.1
  -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 [i386,x86_64]
  ---rootfs         rootfs path
  -h,--help         print this help
EOF
    return 0
}

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

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=1; shift 1;;
        -R|--release)   release=$2; shift 2;;
        -A|--arch)      arch=$2; shift 2;;
        -4|--ipv4)      ipv4=$2; shift 2;;
        -g|--gw)        gw=$2; shift 2;;
        -d|--dns)       dns=$2; shift 2;;
        -u|--user)      default_user=$2; shift 2;;
        --password)     default_user_password=$2; shift 2;;
        --)             shift 1; break ;;
        *)              break ;;
    esac
done

if [ ! -z "$clean" -a -z "$path" ]; then
    clean || exit 1
    exit 0
fi

type apt-get >/dev/null 2>&1
if [ $? -ne 0 ]; then
    echo "'apt-get' command is missing"
    exit 1
fi

type vbootstrap >/dev/null 2>&1
if [ $? -ne 0 ]; then
    echo "'vbootstrap' command is missing"
    exit 1
fi

if [ -z "$path" ]; then
    path=$default_path
fi

if [ -z "$profile" ]; then
    profile=$default_profile
fi

if [ -z "$release" ]; then
    release="VineSeed"
fi

if [ -z "$ipv4" ]; then
    BOOTPROTO="dhcp"
else
    BOOTPROTO="static"
fi

if [ -z "$default_user" ]; then
    default_user="vine"
fi

if [ -z "$default_user_password" ]; then
    default_user_password="vine123"
fi

if [ -z "$arch" ]; then
    arch="$(uname -i)"
fi


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

# check for 'lxc.rootfs' passed in through default config by lxc-create
if [ -z "$rootfs_path" ]; then
    if grep -q '^lxc.rootfs' $path/config 2>/dev/null ; then
        rootfs_path=$(awk -F= '/^lxc.rootfs =/{ print $2 }' $path/config)
    else
        rootfs_path=$path/rootfs
    fi
fi

config_path=$default_path/$name
cache=$cache_base/$arch/$release/$profile

install_vinelinux
if [ $? -ne 0 ]; then
    echo "failed to install vinelinux"
    exit 1
fi

configure_vinelinux
if [ $? -ne 0 ]; then
    echo "failed to configure vinelinux for a container"
    exit 1
fi

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

if [ ! -z "$clean" ]; then
    clean || exit 1
    exit 0
fi
echo "container rootfs and config created"
echo "network configured as $lxc_network_type in the $lxc_network_link"
