#!/bin/bash
# Author: Steven Shiau <steven _at_ nchc org tw>
# License: GPL
# Description: This script will create a Debian live CD iso which is used as a template for clonezilla image with restoration function.

if [ ! -f "/opt/drbl/sbin/drbl-conf-functions" ]; then
  echo "Unable to find /opt/drbl/sbin/drbl-conf-functions! Program terminated!" 
  exit 1
fi
. /opt/drbl/sbin/drbl-conf-functions

# Load some necessary setting from drbl-ocs.conf
. /opt/drbl/conf/drbl-ocs.conf

mirror_url="http://free.nchc.org.tw/ubuntu"
mirror_security_url="http://free.nchc.org.tw/ubuntu"
# debian_type can be minimal (about 67 MB for Etch)/minimal-net (about 85 MB for Etch).
# If we choose to use standard, it will get the DRBL GPG automatically, but
# if using minimal, it will ignore GPG key of DRBL, however, it still can go.
# This can be hacked by modifying /usr/sbin/lh_installapt and more, let it no matter it's minimal or mini, KEY will be loaded. One remaining problem is if using miminal, wget is not installed. Even if minimal-net, wget is installed after lh_installapt... therefore wget is necessary to be installed in lh_installapt. This is done in live-package-0.99.26 in http://free.nchc.org.tw/drbl-core/pool/drbl/live-unstable/ (might change to live-testing or live-stable in the future).
debian_type="minimal"
#debian_type="standard"
DEBIAN_DIST_DEF="gutsy"
pkgs="$PKG_FROM_DBN_WHICH_OCS_LIVE_NEED"

# The files in dir $ocs_live_script_dir/ will be copied to the root (/) dir in dir chroot when make-live/lh_build is run with --include-chroot. The file "ocs-live-hook" is in $ocs_live_script_dir
# We put some files in dir ocs_minimal_hook/ to do some jobs, like clean unnecessary files, set locales...
ocs_live_script_dir="$DRBL_SCRIPT_PATH/setup/files/ocs/live-hook"
# The script inside $ocs_live_script_dir/ will be run when chroot. There are many files in $ocs_live_script_dir/, we will just run one here.
run_hook_script="ocs-live-hook"

#
check_if_root
#
prog="$(basename $0)"

# functions
USAGE() {
    echo "Usage:"
    echo "To create a Debian live CD which is used a template for Clonezilla live:"
    echo "$prog [OPTION]"
    echo "OPTION:"
    echo "-b, --branch [s|stable|t|testing|u|unstable]  specifies the DRBL branch to be used in Live CD. Default is stable."
    echo "-d, --debian-dist [stable|testing|unstable|sarge|etch|sid...]  Assign Debian dist, the default is $DEBIAN_DIST_DEF if not assigned."
    echo "-i, --assign-version-no NO  Assign the version no as NO instead of date."
    echo "-k, --live-kernel-pkg KERNEL_VER Assign kernel version as KERNEL_VER (KERNEL VER package must exist in repository. Ex. if KERNEL_VER is 2.6.20-1-486, then linux-image-2.6.20-1-486, squashfs-modules-2.6.20-1-486, and unionfs-modules-2.6.20-1-486 will be used."
    echo "-l, --drbl-live-branch [s|stable|t|testing|u|unstable|e|experimental]  specifies the DRBL live branch to be used in Live CD. Default is stable."
    echo "-p, --use-backports Include backports in the repository."
    echo "-v, --verbose   Run make-live/lh_build in verbose mode"
}
#
turn_on_etch_backports() {
  # Backports
  # We use etchbpo instead of bpo to avoid being overwritten by the one "bpo" (it's for sarge-backports) in /etc/make-live.conf.
  export LIVE_REPOSITORIES="$LIVE_REPOSITORIES etchbpo"
  export LIVE_REPOSITORY_etchbpo="http://www.backports.org/debian/"
  export LIVE_REPOSITORY_KEY_etchbpo="http://backports.org/debian/archive.key"
  export LIVE_REPOSITORY_KEYRING_etchbpo=""
  export LIVE_REPOSITORY_DISTRIBUTION_etchbpo="etch-backports"
  export LIVE_REPOSITORY_SECTIONS_etchbpo="main contrib non-free"
}

# Parse command-line options
while [ $# -gt 0 ]; do
  case "$1" in
    -b|--branch)
            shift
            if [ -z "$(echo $1 |grep ^-.)" ]; then
              # skip the -xx option, in case 
              drbl_branch="$1"
              shift
            fi
	    [ -z "$drbl_branch" ] && USAGE && exit 1
            ;;
    -d|--debian-dist)
            shift
            if [ -z "$(echo $1 |grep ^-.)" ]; then
              # skip the -xx option, in case 
              debian_dist="$1"
              shift
            fi
	    [ -z "$debian_dist" ] && USAGE && exit 1
            ;;
    -i|--assign-version-no)
            shift
            if [ -z "$(echo $1 |grep ^-.)" ]; then
              # skip the -xx option, in case 
              version_no="$1"
              shift
            fi
	    [ -z "$version_no" ] && USAGE && exit 1
            ;;
    -k|--live-kernel)
            shift
            if [ -z "$(echo $1 |grep ^-.)" ]; then
              # skip the -xx option, in case 
              live_kernel_ver="$1"
              shift
            fi
	    [ -z "$live_kernel_ver" ] && USAGE && exit 1
            ;;
    -l|--drbl-live-branch)
            shift
            if [ -z "$(echo $1 |grep ^-.)" ]; then
              # skip the -xx option, in case 
              drbl_live_branch="$1"
              shift
            fi
	    [ -z "$drbl_live_branch" ] && USAGE && exit 1
            ;;
    -p|--use-backports)
	    use_backports="yes"
            shift ;;
    -v|--verbose)
	    verbose="on"
            shift ;;
    -*)     echo "${0}: ${1}: invalid option" >&2
            USAGE >& 2
            exit 2 ;;
    *)      break ;;
  esac
done

if ! type lh_build &>/dev/null; then
  [ "$BOOTUP" = "color" ] && $SETCOLOR_FAILURE
  echo "This program only works in Ubuntu 7.10 (Gutsy)!"
  echo "If you are running Ubuntu 7.10 or later, use 'apt-get install live-helper' to install the necessary packages, then run $0 again."
  [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
  exit 1
fi

  [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
  echo "///NOTE///"
  echo "1. This script only works in Ubuntu 7.10 (Gutsy) with the live-helper from Gutsy universe (not from Debian Sid)! "
  echo "2. If you want to use cdebootstrap instead of debootstrap, remember to install the one patched by DRBL/Clonezilla team. (Version 0.4.3ubuntu-2 or later from http://opensource.nchc.org.tw/drbl-core/pool/drbl/live-experimental/c/cdebootstrap/)"
  echo "3. You might also need to use the live-experimental from DRBL (i.e. use run $0 with '-l e') so that:"
  echo "  a. Enable aufs instead of unionfs (To avoid this bug: https://bugs.launchpad.net/ubuntu/+source/linux-ubuntu-modules-2.6.22/+bug/150788)."
  echo "  b. Avoid a live-initramfs bug, which fails in console login."
  [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
  echo -n "Press enter to continue... "
  read

rm -rf debian-live/.stage/

[ -z "$debian_dist" ] && debian_dist="$DEBIAN_DIST_DEF"
#if [ -n "$live_kernel_ver" ]; then
  # Ex (1): linux-image-2.6.18-4-486, squashfs-modules-2.6.18-4-486, unionfs-modules-2.6.18-4-486
  # Ex (2): linux-image-2.6.20-1-486, squashfs-modules-2.6.20-1-486, unionfs-modules-2.6.20-1-486,
#  export LIVE_KERNEL_PACKAGES="linux-image-${live_kernel_ver} squashfs-modules-${live_kernel_ver} unionfs-modules-${live_kernel_ver}"
#fi

case "$drbl_branch" in
  t|testing)
     echo "Using DRBL testing branch..."
     LIVE_REPOSITORY_SECTIONS_drbl="stable testing"
     ;;
  u|unstable)
     echo "Using DRBL unstable branch..."
     LIVE_REPOSITORY_SECTIONS_drbl="stable testing unstable"
     ;;
  *)
     echo "Using DRBL stable branch..."
     LIVE_REPOSITORY_SECTIONS_drbl="stable"
     ;;
esac
case "$drbl_live_branch" in
  t|testing)
     echo "Using DRBL Live testing branch..."
     LIVE_REPOSITORY_SECTIONS_drbl="$LIVE_REPOSITORY_SECTIONS_drbl live-stable live-testing"
     ;;
  u|unstable)
     echo "Using DRBL Live unstable branch..."
     LIVE_REPOSITORY_SECTIONS_drbl="$LIVE_REPOSITORY_SECTIONS_drbl live-stable live-testing live-unstable"
     ;;
  e|experimental)
     echo "Using DRBL Live experimental branch..."
     LIVE_REPOSITORY_SECTIONS_drbl="$LIVE_REPOSITORY_SECTIONS_drbl live-stable live-testing live-unstable live-experimental"
     ;;
  *)
     echo "Using DRBL live stable branch..."
     LIVE_REPOSITORY_SECTIONS_drbl="$LIVE_REPOSITORY_SECTIONS_drbl live-stable"
     ;;
esac
export LIVE_REPOSITORY_SECTIONS_drbl

#
[ "$use_backports" = "yes" ] && turn_on_etch_backports

# if version_no is not assigned, use date (Ex. 20070409)
[ -z "$version_no" ] && version_no="$(date +%Y%m%d)"
target_iso="ubuntu-live-for-ocs-${version_no}.iso"

[ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
echo "Creating a Debian live cd iso which is used for clonezilla image with restoration function. The created iso will be in $target_iso" 
[ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL

if [ "$verbose" = "on" ]; then
  pref="bash -x"
fi

if [ -d "debian-live" ]; then
  echo "Found dir debian-live, clean stale debian-live files..."
  chroot debian-live/chroot umount /proc &>/dev/null
  chroot debian-live/chroot umount /sys &>/dev/null
  (
    cd debian-live/
    lh_clean
  )
  rm -rf debian-live
fi

mkdir debian-live
(
cd debian-live

$pref lh_config --sections "main restricted universe multiverse"
$pref lh_config --mirror-binary $mirror_url --mirror-binary-security $mirror_security_url --mirror-bootstrap $mirror_url --mirror-bootstrap-security $mirror_security_url

# Updated! 2007/12/27 with the patch from http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=448210, now we can use cdebootstrap.
# ///OLD/// Here actually we can not use "--bootstrap cdebootstrap" due to this bug:
# ///OLD/// http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=448348&trim=no
# Looks like if we use "--apt apt" instead of "--apt aptitude", there are a lot of warning about failing authenticating deb packages.
$pref lh_config --bootstrap-flavour $debian_type --packages "$pkgs" --includes "$ocs_live_script_dir" --hook /$run_hook_script --apt aptitude --apt-recommends disabled --binary-indices disabled --bootstrap cdebootstrap --tasksel none
#$pref lh_config --username casper --bootappend username=casper --initramfs casper
# Since casper does not support aufs, and we need aufs to avoid this bug: 
# https://bugs.launchpad.net/ubuntu/+source/linux-ubuntu-modules-2.6.22/+bug/150788. Comment this:
# Due to a bug in Ubuntu 7.10, we can only use "--initramfs casper". If we use "--initramfs live-initramfs", the created iso won't boot into command line. Some errors like:
# init:/etc/event.d/tty1:15: Unknown stanza
# will occur when booting, so upstart won't run gettty
#$pref lh_config --initramfs casper
#$pref lh_config --linux-flavours generic --linux-packages "linux-restricted-modules"

if [ "$debian_dist" = "etch" ] || [ "$debian_dist" = "stable" ]; then
	$pref lh_config --distribution $debian_dist --union-filesystem unionfs --linux-packages "linux-image-2.6 unionfs-modules-2.6 squashfs-modules-2.6" --initramfs casper
else
	# For Ubuntu 7.10, only unionfs comes with kernel, no aufs. However, we need aufs to avoid a bug (see above). An aufs module provided by DRBL works for this.
	# $pref lh_config --distribution $debian_dist --union-filesystem aufs --linux-packages "linux-image${kernel_extra_tag} aufs-modules${kernel_extra_tag} squashfs-modules${kernel_extra_tag}" 
	# For gutsy: linux-image-2.6.22-14-386
	# Live helper auto append "-386" for param from "--linux-packages"
	# TODO: UGLY! 2.6.22-14 should not be hardcoded in this program. We should find a better solution to work with kernel and aufs module.
	$pref lh_config --distribution $debian_dist --union-filesystem aufs --linux-packages "linux-image-2.6.22-14 linux-ubuntu-modules-2.6.22-14 aufs-modules-2.6.22-14"
fi

# exclude some stuffs from the squashfs root, since in Live system, we will only use vmlinuz and initrd in /casper, not in the /boot/ in the squashfs.
export MKSQUASHFS_OPTIONS="-e boot"

cp -p $ocs_live_script_dir/* config/chroot_local-includes/

# prepare drbl source list
cat << AddDRBLRepository > config/chroot_sources/drbl.bootstrap
#deb http://free.nchc.org.tw/ubuntu/ gutsy-updates main restricted universe multiverse
#deb http://free.nchc.org.tw/ubuntu/ gutsy-backports main restricted universe multiverse
#deb http://free.nchc.org.tw/ubuntu/ gutsy-proposed main restricted universe multiverse
deb http://free.nchc.org.tw/drbl-core drbl $LIVE_REPOSITORY_SECTIONS_drbl
AddDRBLRepository

# prepare drbl key
LANG=C wget -O config/chroot_sources/drbl.bootstrap.gpg http://drbl.nchc.org.tw/GPG-KEY-DRBL

$pref lh_build
)
mv -f debian-live/binary.iso $target_iso
