#!/bin/sh
#
#  Copyright (c) 2009 Canonical
#
#  Author: Oliver Grawert <ogra@canonical.com>
#
#  This program is free software; you can redistribute it and/or
#  modify it under the terms of the GNU General Public License as
#  published by the Free Software Foundation; either version 2 of the
#  License, or (at your option) any later version.
#
#  This program 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 General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program; if not, write to the Free Software
#  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
#  USA
#
######################################################################
# This script creates a tgz file of an armel rootfs you can untar in #
# a partition for your target hardware (beagleboard, EVM or freescale#
# board were tested with this yet)                                   #
# See https://wiki.ubuntu.com/ARM/RootfsFromScratch for more details #
######################################################################
#
# TODO: - install langpacks for selected locale
#
######################################################################

set -e

trap cleanup 1 2 3 6 15

cleanup()
{
      echo "I: Cleaning up..."
      echo "I: Killed ... " >>$LOG 2>&1

      # kill debootstrap if its running
      if [ -e ${DBPID} ];then
          DPID=$(cat ${DBPID})
          kill -9 $DPID >/dev/null 2>&1
      fi

      # kill qemu if its running
      if [ -e ${QEMUPID} ];then
          QPID=$(cat ${QEMUPID})
          kill -9 $QPID >/dev/null 2>&1
      fi

      for i in 1 2 3 4 5; do
          echo -n '.'
          sleep 1
      done
      echo
      savelog

      # unmount loop mount
      if [ "$(mount| grep ${MOUNTPOINT})" ];then
          umount -l $MOUNTPOINT
      fi

      # unmount tmpfs for swap
      if [ -n "$TMPMOUNT" ];then
          if $(mount |grep -q $TMPMOUNT);then
              umount -l $TMPMOUNT
          fi
      fi

      # wipe builddir
      rm -rf $BUILDDIR
      echo "I: done ..."
      exit 0
}

usage()
{
    echo "usage: $(basename $0) -f <hostname> -l <login name> -p <password> [option]"
cat <<EOF

required options:
-f --fqdn <hostname>
    Hostname to be used for the target system

additional options:
-l --login <login name>
    Login ID of the admin user created during setup
-p --password <password>
    Password of the admin user created during setup
-h --help
    this help
-n --fullname <quoted string>
    Full Name of the admin user created during setup
    (default: "Ubuntu System User")
-s --seed <csv list>
    List of packages to install (i.e. ubuntu-desktop)
-i --imagesize <size>M/G
    Size of the target filesystem to be created (i.e. 500M)
    (default: 1G)
-g --manifest <path to file>
    Manifest file with list of packages to install (one per line)
-m --mirror <url>
    apt mirror to use (i.e. http://ports.ubuntu.com/ubuntu-ports)
    (default: http://ports.ubuntu.com/ubuntu-ports)
-c --components <csv list>
    Archive components
    (default: main,universe)
-d --dist (jaunty or karmic)
    Specify Release to build
    (default: `lsb_release -cs`)
-t --timezone <timezone>
    Timezone for the system (i.e. Europe/Berlin)
    (default: buildsystem timezone)
-x --locale <locale.encoding>
    Language used in the installed system (i.e. en_US.UTF-8)
    (default: buildsystem locale)
--script <filename>
    Run this script at the end of the installation process
--serial <devicename>
    Create a serial tty of <devicename> inside the rootfs for login (i.e. ttyS0)
--doswap
    Do create a swapfile in tmpfs for the virtual machine
--swapsize <size in megabyte>
    Use a different size for the swapfile used by the virtual machine
    (default: 256M)

keyboard options:
--kblayout <layout>
    Keyboard layout (i.e. us)
    (default: buildsystem kblayout)
--kbmodel <model>
    Keyboard model (i.e. pc105)
    (default: buildsystem kbmodel)
--kbvariant <variant>
    Keyboard variant (i.e. nodeadkeys)
    (default: buildsystem kbvariant)
--kboptions <options>
    Additional keyboard options
    (default: buildsystem kboptions)

output options:
--keepimage
    Keep the qemu image instead of deleting it
--notarball
    Do not roll a tarball of the rootfs (autosets --keepimage)

extra parameters:
-q --quiet
    Quiet operation, only write to log

advanced options:
--kernel-image <http url to kernel .deb>
    install board specfic kernel package from http accessible deb package inside rootfs
--copy-package-cache
    save a snapshot of all packages used for a build locally to re-use them
    in a subsequent offline build with the --restore-package-cache option
--restore-package-cache
    use precached packages from a former build run with --copy-package-cache
--clean-package-cache
    empty the package cache of a former --copy-package-cache run
--extra-mirror
    additional mirror to use
EOF
    exit 0
}

checkparm()
{
    if [ "$(echo $1|grep ^'\-')" ];then
        echo "E: Need an argument"
        usage
    fi
}

savelog()
{
    if [ -z "$NOSAVELOG" ];then
        mv $LOG $DIR/
        echo "I: A logfile was saved as $DIR/$(basename $0)-$STAMP.log"
    fi
}

create_raw_image()
{
    [ $QUIET ] || echo "I: Creating temporary Image"
    LANG=C qemu-img create $IMAGENAME $IMAGESIZE >$LOG 2>&1
    LANG=C mkfs.ext3 -F $IMAGENAME >>$LOG 2>&1
    VOLID=$(blkid -o value $IMAGENAME|head -1)
}

mount_image()
{
    [ $QUIET ] || echo "I: Mounting temporary Image"
    if [ ! -d $MOUNTPOINT ];then
        mkdir -p $MOUNTPOINT >>$LOG 2>&1
    fi
    mount -o loop $IMAGENAME $MOUNTPOINT >>$LOG 2>&1
}

run_first_stage()
{
    [ $QUIET ] || echo "I: Running first stage"

    mkfifo $DBFIFO

    EXTRAOPTS=""
    TARBALL=$CACHEDIR/debootstrap.tgz
    DMIRROR="$MIRROR"
    DEFOPTS="--foreign --arch=armel"

    if [ "$RESTORE_PACKAGE_CACHE" ];then
        if [ ! -d $CACHEDIR ];then
            echo "I: Error, no pre-cached packages found !"
            echo "I: please run rootstock with --copy-package-cache first"
            NOSAVELOG=1
            cleanup
        fi
        [ $QUIET ] || echo "I: using pre-cached packages"
        EXTRAOPTS="--unpack-tarball=$TARBALL"
        DMIRROR="file://$CACHEDIR"
    fi

    if [ "$COPY_PACKAGE_CACHE" ];then
        [ $QUIET ] || echo "I: pre-caching debootstrap packages"
        EXTRAOPTS="--keep-debootstrap-dir --make-tarball=$TARBALL"
        mkdir -p $CACHEDIR

        LANG=C debootstrap $DEFOPTS $EXTRAOPTS $DIST $MOUNTPOINT $DMIRROR >$DBFIFO 2>&1 &
        echo $! > $DBPID
        while read line; do
            echo ${line} >>$LOG 2>&1
            if [ ! "$QUIET" ];then
                echo "${line}"
            fi
        done <$DBFIFO

        EXTRAOPTS="--unpack-tarball=$TARBALL"
    fi

    LANG=C debootstrap $DEFOPTS $EXTRAOPTS $DIST $MOUNTPOINT $DMIRROR >$DBFIFO 2>&1 &

    echo $! > $DBPID
    while read line; do
        echo ${line} >>$LOG 2>&1
        if [ ! "$QUIET" ];then
            echo "${line}"
        fi
    done <$DBFIFO

    if [ "$COPY_PACKAGE_CACHE" ];then
        mkdir -p $CACHEDIR/dists/$DIST
        cp $MOUNTPOINT/var/lib/apt/lists/*Release $CACHEDIR/dists/$DIST/Release
    fi

    if [ ! $(which qemu-arm-static) ];then
        SECOND_STAGE="/debootstrap/debootstrap --second-stage"
    else
        mkdir -p $MOUNTPOINT/usr/bin/
        cp $(which qemu-arm-static) $MOUNTPOINT/usr/bin/
        chroot $MOUNTPOINT debootstrap/debootstrap --second-stage >$DBFIFO 2>&1 &
        SECOND_STAGE=""

		echo $! > $DBPID
		while read line; do
			echo ${line} >>$LOG 2>&1
			if [ ! "$QUIET" ];then
				echo "${line}"
			fi
		done <$DBFIFO
    fi

    rm -f $DBFIFO
    rm -f $DBPID

    [ $QUIET ] || echo "I: First stage install done"
}

run_vm()
{
    # get kernel
    [ $QUIET ] || echo "I: Getting Virtual Machine kernel from the server"
    get_vm_kernel

    mkfifo $QEMUFIFO

    [ $QUIET ] || echo "I: Switching to Virtual Machine for second stage processing"
    VMCPU="cortex-a8"
    if [ -n "$SWAPFILE" ];then
        SWAPDEV="-hdb $SWAPFILE"
    fi
    QEMUOPTS="-M versatilepb ${VMCPU:+-cpu $VMCPU} -kernel ${BUILDDIR}/qemu-vmlinuz -no-reboot -nographic -pidfile ${QEMUPID} -drive file=${IMAGENAME},aio=native,cache=none ${SWAPDEV} -m 256"
    APPEND="console=ttyAMA0,115200n8 root=/dev/sda rw mem=256M devtmpfs.mount=0 init=/bin/installer quiet"

    qemu-system-arm $QEMUOPTS -append "${APPEND}" >$QEMUFIFO 2>&1 &

    while read line; do
        if [ "$(echo $line|grep panic)" ];then
            echo ${line} >>$LOG 2>&1
            echo "E: Second stage build in Virtual Machine failed !"
            echo "E: Please see the log to see what went wrong."
            cleanup
        fi
        if [ "$line" ] && [ ! "$(echo $line|grep 'Uncompressing Linux')" ] && \
            [ ! "$(echo $line|grep 'unknown LCD panel')" ] && \
            [ ! "$(echo $line|grep 'Restarting system')" ];then
            echo ${line} >>$LOG 2>&1
            if [ ! "$QUIET" ];then
                echo "${line}"
            fi
        fi
    done <$QEMUFIFO

    rm -f $QEMUPID

    [ $QUIET ] || echo "I: Virtual Machine done"
}

setup_serial()
{
    [ $QUIET ] || echo "I: Setting up serial tty in image"

    if [ "$DIST" = "jaunty" ];then
        test -d $MOUNTPOINT/etc/event.d/|| mkdir -p $MOUNTPOINT/etc/event.d/
        cat > $MOUNTPOINT/etc/event.d/$SERIAL_TTYS <<EOF
start on runlevel 2
start on runlevel 3
start on runlevel 4
start on runlevel 5

stop on runlevel 0
stop on runlevel 1
stop on runlevel 6

respawn
exec /sbin/getty 115200 $SERIAL_TTYS
EOF
    else
        test -d $MOUNTPOINT/etc/init/|| mkdir -p $MOUNTPOINT/etc/init/
        cat > $MOUNTPOINT/etc/init/$SERIAL_TTYS.conf <<EOF
start on stopped rc RUNLEVEL=[2345]
stop on runlevel [!2345]

respawn
exec /sbin/getty 115200 $SERIAL_TTYS
EOF
    fi
}

use_swap()
{
    TMPMOUNT=$BUILDDIR/tmpfs
    SWAPFILE=$TMPMOUNT/swapfile
    [ $QUIET ] || echo "I: Creating swapfile in tmpfs for VM"
    mkdir -p $TMPMOUNT >>$LOG 2>&1
    mount -t tmpfs -o size=$(($SWAPSIZE*1048576)) tmpfs $TMPMOUNT >>$LOG 2>&1
    dd if=/dev/zero of=$SWAPFILE bs=1048576 count=$(($SWAPSIZE-8)) >>$LOG 2>&1
    mkswap -f $SWAPFILE >>$LOG 2>&1
    SWAPCMD="swapon /dev/sdb"
}

setup_kernel_image()
{
    [ $QUIET ] || echo "I: Downloading kernel image (deb) from external site"

    mkdir -p $DIR/dl/
    wget --directory-prefix=$DIR/dl/ --quiet $KERNEL_IMG

    KERNEL_IMG=${KERNEL_IMG##*/}

    test -d $MOUNTPOINT/tmp/|| mkdir -p $MOUNTPOINT/tmp/
    cp $DIR/dl/$KERNEL_IMG  $MOUNTPOINT/tmp

    [ $QUIET ] || echo "I: $KERNEL_IMG download complete"
    #Hack dpkg -i fails, no postinstall script is run anyways, so lets just extract it.
    KERNEL_IMAGE_CMD="dpkg -x /tmp/$KERNEL_IMG /"

    KERNEL_IMG_REL=${KERNEL_IMG##*linux-image-}
    KERNEL_IMG_REL=${KERNEL_IMG_REL/_*_armel.deb}

    KERNEL_IMAGE_CREATE_INITRAMFS="update-initramfs -c -k $KERNEL_IMG_REL"
}

get_vm_kernel()
{
    if [ "$RESTORE_PACKAGE_CACHE" ];then
        cp $CACHEDIR/vmkernel/qemu-vmlinuz $BUILDDIR/qemu-vmlinuz
    else
        KERNEL="http://ports.ubuntu.com/ubuntu-ports/dists/lucid/main/installer-armel/current/images/versatile/netboot/vmlinuz"
        LANG=C wget -O $BUILDDIR/qemu-vmlinuz $KERNEL >>$LOG 2>&1
        if [ "$COPY_PACKAGE_CACHE" ];then
            mkdir -p $CACHEDIR/vmkernel/
            cp $BUILDDIR/qemu-vmlinuz $CACHEDIR/vmkernel/
        fi
    fi
}

extract_kernel_image()
{
    [ $QUIET ] || echo "I: Extracting vmlinuz from *.deb"
    mkdir -p $DIR/dl/tmp/
    dpkg -x $DIR/dl/$KERNEL_IMG $DIR/dl/tmp/
    cp $DIR/dl/tmp/boot/vmlinuz-* $DIR
    rm -rfd $DIR/dl/
    cp $MOUNTPOINT/boot/initrd.img-* $DIR
    [ $QUIET ] || echo "I: vmlinuz & initrd.img ready for (mkimage/etc) tool"
}

clean_package_cache()
{
    [ $QUIET ] || echo "I: Removing cached files"
    rm -rf $CACHEDIR/*
    cleanup
}

save_package_cache()
{
    [ $QUIET ] || echo "I: caching packages for later use"

    mount_image

    mkdir -p $CACHEDIR
    cp -up $MOUNTPOINT/var/cache/apt/archives/*.deb $CACHEDIR/ || true


    mkdir -p $CACHEDIR/lists
    cp -p $MOUNTPOINT/var/lib/apt/lists/* $CACHEDIR/lists/ || true

    chroot $MOUNTPOINT apt-get clean

    umount $MOUNTPOINT
}

restore_package_cache()
{
    [ $QUIET ] || echo -n "I: restoring cached packages"


    mkdir -p $MOUNTPOINT/var/cache/apt/archives
    i=0
    cp -vp $CACHEDIR/*.deb $MOUNTPOINT/var/cache/apt/archives/ | \
                while read line ; do
                    if [ "$i" -ge "5" ]; then
                        [ $QUIET ] || echo -n .
                        i=0
                    else
                        i=$(($i+1))
                    fi
                done
                [ $QUIET ] || echo
    mkdir -p $MOUNTPOINT/var/lib/apt/lists/
    cp -p $CACHEDIR/lists/* $MOUNTPOINT/var/lib/apt/lists/ || true
    APT_UPDATE=""
    APT_FORCE="--allow-unauthenticated"
}

add_extra_mirror()
{
    EXRA_MIRROR_CMD="echo \"deb ${EXTRAMIRROR} ${DIST} ${COMPONENTS}\" >>/etc/apt/sources.list"
}

roll_tarball()
{
    # create a rootfs tgz
    [ $QUIET ] || echo "I: Creating tarball from rootfs"

    mount_image

    cd $MOUNTPOINT >>$LOG 2>&1
    LANG=C tar czvf ../armel-rootfs-$STAMP.tgz . >>$LOG 2>&1
    mv ../armel-rootfs-$STAMP.tgz $DIR >>$LOG 2>&1

    echo "I: ARM rootfs created as $DIR/armel-rootfs-$STAMP.tgz"

    cd - >/dev/null 2>&1
}

save_qemu_img()
{
    cp $IMAGENAME $DIR
    if [ "$SUDO_USER" ]; then
        chown $SUDO_USER $DIR/qemu-armel-$STAMP.img
    fi
    echo "I: Qemu image saved as $DIR/qemu-armel-$STAMP.img"
}

# target system name
FQDN=""

# target user
NEWUSER=""
FULLNAME="Ubuntu System User"
PASSWD=""

# target package selection
SELECTION="" # change here to install ubuntu-desktop
IMAGESIZE="1G" # make this 3G for an ubuntu-desktop install

# default to the build system locale
. /etc/environment
. /etc/default/locale
NEWLOCALE=$LANG

# default to the build system keyboard setup
KBDATA="/etc/default/console-setup"
XKBL=$(grep XKBLAYOUT ${KBDATA}|tr -d '"'|cut -d '=' -f2)
XKBM=$(grep XKBMODEL ${KBDATA}|tr -d '"'|cut -d '=' -f2)
XKBV=$(grep XKBVARIANT ${KBDATA}|tr -d '"'|cut -d '=' -f2)
XKBO=$(grep XKBOPTIONS ${KBDATA}|tr -d '"'|cut -d '=' -f2)

# default to the build system timezone
TZONE=$(cat /etc/timezone)

# target apt setup
DIST=$(lsb_release -cs)
MIRROR="http://ports.ubuntu.com/ubuntu-ports"
COMPONENTS="main universe"

# user-specified script
USER_SCRIPT=""

# builder defaults
DEFGROUPS="admin,adm,dialout,cdrom,floppy,audio,dip,video"
STAMP=$(date +%Y%m%d%H%M)
BUILDDIR=$(mktemp -d)
MOUNTPOINT="${BUILDDIR}/tmpmount"
IMAGENAME="${BUILDDIR}/qemu-armel-$STAMP.img"
QEMUPID="${BUILDDIR}/qemu.pid"
QEMUFIFO="${BUILDDIR}/qemufifo"
DBPID="${BUILDDIR}/debootstrap.pid"
DBFIFO="${BUILDDIR}/dbfifo"
DIR="$(pwd)"
NOSWAP=1
SWAPSIZE=256

# general defaults
LOG="$BUILDDIR/$(basename $0)-$STAMP.log"

PACKAGE_CLEANUP="apt-get clean"
PACKAGE_CLEANUP_SUB="${PACKAGE_CLEANUP}"
APT_UPDATE="apt-get update"
APT_FORCE=""
CACHEDIR="/var/cache/rootstock/archives"
EXRA_MIRROR_CMD=""

# we need root
if [ $(id -u) != 0 ];then
    echo "must be run as root"
    exit 2
fi

if [ ! $(which qemu-system-arm) ];then
    echo "qemu not installed, please use:"
    echo "sudo apt-get install qemu"
    echo "(or on ubuntu > karmic sudo apt-get install qemu-kvm-extras)"
    echo "to install the qemu package !"
    exit 1
fi

if [ ! $(which debootstrap) ];then
    echo "debootstrap not installed, please use:"
    echo "sudo apt-get install debootstrap"
    echo "to install the debootstrap package !"
    exit 1
fi

# parse commandline options
while [ ! -z "$1" ]; do
    case $1 in
        -h|--help)
            usage
            ;;
        -f|--fqdn)
            checkparm $2
            FQDN="$2"
            ;;
        -l|--login)
            checkparm $2
            NEWUSER="$2"
            ;;
        -p|--password)
            checkparm $2
            PASSWD="$2"
            ;;
        -n|--fullname)
            checkparm $2
            FULLNAME="$2"
            ;;
        -s|--seed)
            checkparm $2
            SELECTION="$(echo $2|tr ',' ' ')"
            ;;
        -i|--imagesize)
            checkparm $2
            if [ ! "$(echo $2|grep 'M')" ] && \
                [ ! "$(echo $2|grep 'G')" ];then
                echo "E: Size needs to be in gigabyte or megabyte"
                usage
            fi
            IMAGESIZE="$2"
            ;;
        -g|--manifest)
            checkparm "${2}"
            SELECTION="$(cat "${2}" | sed ':a;N;$!ba;s/\n/ /g')"
            ;;
        -m|--mirror)
            checkparm $2
            MIRROR="$2"
            ;;
        -c|--components)
            checkparm $2
            COMPONENTS="$(echo $2|tr ',' ' ')"
            ;;
        -t|--timezone)
            checkparm $2
            if [ ! "$(echo $2|grep '/')" ];then
                echo "E: Need a proper timezone"
                usage
            fi
            TZONE="$2"
            ;;
        --kblayout)
            checkparm $2
            XKBL="$2"
            ;;
        --kbmodel)
            checkparm $2
            XKBM="$2"
            ;;
        --kbvariant)
            checkparm $2
            XKBV="$2"
            ;;
        --kboptions)
            checkparm $2
            XKBO="$2"
            ;;
        -x|--locale)
            checkparm $2
            if [ ! "$(echo $2|grep '_')" ];then
                echo "E: Need a proper locale"
                usage
            fi
            NEWLOCALE="$2"
            ;;
        --keepimage)
            KEEPIMAGE=1
            ;;
        --notarball)
            NOTARBALL=1
            KEEPIMAGE=1
            ;;
        --script)
            checkparm $2
            USER_SCRIPT="$2"
            ;;
        --serial)
            checkparm $2
            if [ ! "$(echo $2)" ];then
                SERIAL_TTYS="ttyS0"
            else
                SERIAL_TTYS="$2"
            fi
            SERIAL=1
            ;;
        --doswap)
            NOSWAP=""
            ;;
        --swapsize)
            checkparm $2
            SWAPSIZE="$2"
            ;;
        -d|--dist)
            checkparm $2
            DIST="$2"
            ;;
        -q|--quiet)
            QUIET=1
            ;;
        --kernel-image)
            checkparm $2
            KERNEL_IMAGE=1
            KERNEL_IMG="$2"
            ;;
        --copy-package-cache)
            COPY_PACKAGE_CACHE=1
            PACKAGE_CLEANUP=""
            PACKAGE_CLEANUP_SUB=""
            ;;
        --restore-package-cache)
            RESTORE_PACKAGE_CACHE=1
            APT_UPDATE=""
            PACKAGE_CLEANUP=""
            ;;
        --clean-package-cache)
            CLEAN_PACKAGE_CACHE=1
            NOSAVELOG=1
            ;;
        --extra-mirror)
            checkparm $2
            EXTRAMIRROR=$2
            ;;
    esac
    shift
done

if [ ! -f /usr/share/debootstrap/scripts/$DIST ];then
  echo "Your debootstrap installation does not seem to have support for the $DIST distribution"
  exit 5
fi

# process vars
AREA=${TZONE%%/*}
ZONE=${TZONE#*/}

# check if we have at least hostname, login and password

if [ ! "${FQDN}" ];then
    usage
fi

PW=$(perl -e 'print crypt($ARGV[0], "qemuonarm")', $PASSWD)

USERADD_CMD="useradd -G ${DEFGROUPS} -s /bin/bash -m -p ${PW} -c \"${FULLNAME}\" ${NEWUSER} || true"
if [ ! "${NEWUSER}" ] || [ ! "${PASSWD}" ];then
    USERADD_CMD='PACKAGE="oem-config"
echo "I: Enabling firstboot configuration"
if [ -n "$(dpkg -l xserver-xorg 2>/dev/null|grep ^ii)" ];then
    if [ $(which gdm) ];then
        PACKAGE="oem-config-gtk"
    elif [ $(which kdm) ];then
        PACKAGE="oem-config-kde"
    fi
fi

apt-get install -y --no-install-recommends $PACKAGE'
    OEM_CONFIG_ENABLE="touch /var/lib/oem-config/run
rm /usr/lib/ubiquity/plugins/ubi-tasks.py*"
fi

if [ "$CLEAN_PACKAGE_CACHE" ];then
    clean_package_cache
fi

create_raw_image
mount_image
run_first_stage

# restore cached packages from host machine
if [ "$RESTORE_PACKAGE_CACHE" ];then
    restore_package_cache
fi

if [ "$EXTRAMIRROR" ];then
    add_extra_mirror
fi

# basic fstab
echo "proc /proc proc defaults 0 0" >$MOUNTPOINT/etc/fstab
if [ "$KEEPIMAGE" ];then
    echo "UUID=${VOLID} / auto errors=remount-ro 0 1" >>$MOUNTPOINT/etc/fstab
fi

if [ -e /etc/apt/apt.conf.d/proxy ];then
    mkdir -p $MOUNTPOINT/etc/apt/apt.conf.d
    cp /etc/apt/apt.conf.d/proxy $MOUNTPOINT/etc/apt/apt.conf.d/proxy
fi

if [ "$http_proxy" ];then
    PROXY=$http_proxy
fi

# set up basic networking
NETWORKDIR="$MOUNTPOINT/etc/network"
INTERFACES="$NETWORKDIR/interfaces"
mkdir -p $NETWORKDIR

echo "auto lo" >$INTERFACES
echo "iface lo inet loopback" >>$INTERFACES

# set up resolver
HOSTS="$MOUNTPOINT/etc/hosts"
echo "127.0.0.1 localhost" >$HOSTS
echo "127.0.1.1 ${FQDN}" >>$HOSTS

echo "${FQDN}" >$MOUNTPOINT/etc/hostname

if [ "$KERNEL_IMAGE" ];then
    setup_kernel_image
fi

# write installer script to image
cat > $BUILDDIR/installer <<EOF
#!/bin/bash
set -e

export MALLOC_CHECK_=0 # workaround for LP: #520465
export PATH
export LC_ALL=C
export DEBIAN_FRONTEND=noninteractive
export http_proxy="${PROXY}"

${SECOND_STAGE}

echo "I: Starting basic services in VM"

mount -t proc proc /proc
mount -t sysfs sys /sys
mkdir -p /dev/pts
mount -t devpts devpts /dev/pts

udevd --daemon &

hostname -F /etc/hostname

dpkg-divert --add --local --divert /usr/sbin/invoke-rc.d.rootstock --rename /usr/sbin/invoke-rc.d
cp /bin/true /usr/sbin/invoke-rc.d

${SWAPCMD}

echo "deb ${MIRROR} ${DIST} ${COMPONENTS}" >/etc/apt/sources.list
${EXRA_MIRROR_CMD}

ifconfig lo up
ifconfig eth0 up
dhclient eth0

locale-gen --no-purge en_GB.UTF-8 || true
locale-gen --no-purge ${NEWLOCALE} || true
echo LANG=${NEWLOCALE} >>/etc/default/locale

sed -i -e 's/^XKBMODEL=.*\$/XKBMODEL="${XKBM}"/' /etc/default/console-setup || true
sed -i -e 's/^XKBLAYOUT=.*\$/XKBLAYOUT="${XKBL}"/' /etc/default/console-setup || true
sed -i -e 's/^XKBVARIANT=.*\$/XKBVARIANT="${XKBV}"/' /etc/default/console-setup || true
sed -i -e 's/^XKBOPTIONS=.*\$/XKBOPTIONS="${XKBO}"/' /etc/default/console-setup || true

echo ${AREA}/${ZONE} > /etc/timezone
cp -f /usr/share/zoneinfo/${AREA}/${ZONE} /etc/localtime || true

groupadd fuse || true

${APT_UPDATE}

${PACKAGE_CLEANUP}

PKGCOUNT=\$(LANG=C apt-get -s install ${SELECTION} |grep "newly installed"|cut -d ',' -f2|tr -d ' [a-z]')
echo "packagecount=\${PKGCOUNT:-1}"
[ -z "${SELECTION}" ] || apt-get -y ${APT_FORCE} install ${SELECTION}

${KERNEL_IMAGE_CMD}
${KERNEL_IMAGE_CREATE_INITRAMFS}

groupadd admin || true

echo '%admin  ALL=(ALL) ALL' >>/etc/sudoers

${USERADD_CMD}

${OEM_CONFIG_ENABLE}

${PACKAGE_CLEANUP_SUB}

passwd -l root || true

rm -f /usr/sbin/invoke-rc.d
dpkg-divert --remove --rename /usr/sbin/invoke-rc.d

if [ -x /rootstock-user-script ]; then
    /rootstock-user-script
    rm -f /rootstock-user-script
fi

mount -n -o remount,ro -t ext3 /dev/sda / || true

rm /bin/installer && reboot -fp

EOF

# copy over user script
if [ "$USER_SCRIPT" ]; then
    cp "$USER_SCRIPT" "$MOUNTPOINT/rootstock-user-script"
fi

if [ "$SERIAL" ];then
    setup_serial
fi

if [ ! "$NOSWAP" ];then
    use_swap
fi

mv $BUILDDIR/installer $MOUNTPOINT/bin/ >>$LOG 2>&1
chmod +x $MOUNTPOINT/bin/installer >>$LOG 2>&1

# make sure we're not mounted
umount $MOUNTPOINT >>$LOG 2>&1

# run vm for second stage
run_vm

# cache packages on host machine
if [ "$COPY_PACKAGE_CACHE" ];then
    save_package_cache
fi

# build a rootfs tarball
if [ ! "$NOTARBALL" ];then
    roll_tarball
fi

# save a qemu image
if [ "$KEEPIMAGE" ];then
    save_qemu_img
fi

# create boot image
if [ "$KERNEL_IMAGE" ];then
    extract_kernel_image
fi

# clean up and save a log
cleanup
