#!/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

mirror_url="http://free.nchc.org.tw/debian"
mirror_security_url="http://free.nchc.org.tw/debian-security/"
# debian_type can be minimal (about 67 MB for Etch)/minimal-net (about 85 MB for Etch).
debian_type="minimal"
debian_dist="etch"
pkgs="$PKG_FROM_DBN_MINIMAL_NEED $PKG_FROM_DBN_WHICH_OCS_LIVE_NEED"
target_iso="debian-live-for-ocs-`date +%Y%m%d`.iso"
ocs_live_script="$DRBL_SCRIPT_PATH/setup/files/ocs/live-chroot"
# The script will be run when chroot
minimal_hook_script="/minimal_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 "-v, --verbose   Run make-live in verbose mode"
}

# Parse command-line options
while [ $# -gt 0 ]; do
  case "$1" in
    -v|--verbose)
	    verbose="on"
            shift ;;
    -*)     echo "${0}: ${1}: invalid option" >&2
            USAGE >& 2
            exit 2 ;;
    *)      break ;;
  esac
done

if ! type make-live &>/dev/null; then
  [ "$BOOTUP" = "color" ] && $SETCOLOR_FAILURE
  echo "This script only works in Debian Etch or later!"
  echo "If you are running Debian Etch or later, use 'apt-get install live-package' to install it."
  [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
  exit 1
fi

[ "$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

rm -rf debian-live/.stage/

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

# add the script in /usr/share/make-live/hooks/minimal
if ! grep -q "$minimal_hook_script" /usr/share/make-live/hooks/minimal; then
 echo "$minimal_hook_script" >> /usr/share/make-live/hooks/minimal
fi
$pref make-live --mirror $mirror_url --mirror-security $mirror_security_url --distribution $debian_dist --flavour $debian_type --packages "$pkgs" --include-chroot "$ocs_live_script"
# remove the script in /usr/share/make-live/hooks/minimal
perl -i -ne "print unless /^$minimal_hook_scriptipt_3/ .. /.*$/" /usr/share/make-live/hooks/minimal
mv -f debian-live/binary.iso $target_iso
