#!/bin/bash -e
# Copyright (c) 2011 Adrian Moya <adrian@turnkeylinux.org> - all rights reserved
# This script is a modified version of tklpatch by Alon Swartz <alon@turnkeylinux.org>
# The work is inspired in the work and ideas of Jeremy Davis <jedmeister@turnkeylinux.org>
# The script will convert a turnkelinux iso into an ovz template.

fatal() {
    echo "fatal: $@" 1>&2
    exit 1
}

usage() {
cat<<EOF
Syntax: $(basename $0) image.iso 
Convert an ISO into an OVZ template

tkliso2ovz will make use of some of the tklpatch scripts to convert an iso to an OVZ template

This is the top high level script, which calls:

    1) tklpatch-extract-iso         
       Disassemble the ISO to extract its contents

    2) tklpatch-apply ovz.tar.gz              
       Apply the ovz patch to the root filesystem. 

    3) tklpatch-gen-ovztemplate
       Compress the root filesystem and create the final template.

Environment variables:

    TKLPATCH_DEBUG       

      Turn on debugging: this makes tklpatch more verbose and prevents
      deletion of temporary directories.

Example usage:

    TKLPATCH_DEBUG=y tkliso2ovz path/to/turnkey-core.iso 

EOF
    exit 1
}

if [[ "$#" != "1" ]]; then
    usage
fi

[ "$(id -u)" != "0" ] && fatal "must be run as root"

isofile=$1
patch=tklovz.tar.gz

if ! [[ -f $isofile || -f /srv/tklpatch/base-images/$isofile ]]; then
    fatal "no such file '$isofile;"
fi

if ! [[ -f $patch || -f /usr/local/share/tklpatch/$patch ]]; then
    fatal "Can't find the tklovz patch"                                        
fi

[ -n "$TKLPATCH_DEBUG" ] && set -x

name="$(basename $isofile)"
name="$(echo $name | sed 's/.iso$//')"

rootfs=$name.rootfs
cdroot=$name.cdroot

# check if final template exists
if [ -f $name-ovz.tar.gz ]; then
   fatal "$name-ovz.tar.gz already exists"
fi

# check if files are local or in /srv/tklpatch
if ! [ -f $isofile ]; then
    isofile=/srv/tklpatch/base-images/$isofile
fi

# check if patch is local or in /usr/local/share/tklpatch
if ! [ -f $patch ]; then
    patch=/usr/local/share/tklpatch/tklovz.tar.gz
fi

DATETIME=`date +%d-%m-%y\ %H:%M:%S`
echo "tkliso2ovz run at $DATETIME" > /var/log/tklpatch/$name-ovz.log
tklpatch-extract-iso $isofile | tee -a /var/log/tklpatch/$name-ovz.log
tklpatch-apply $rootfs $patch | tee -a /var/log/tklpatch/$name-ovz.log
tklpatch-gen-ovztemplate $rootfs | tee -a /var/log/tklpatch/$name-ovz.log

# delete temporary rootfs and cdroot unless TKLCONV_DEBUG
[ -z "$TKLPATCH_DEBUG" ] && rm -rf $rootfs
[ -z "$TKLPATCH_DEBUG" ] && rm -rf $cdroot

echo "Log created at /var/log/tklpatch/$name-ovz.log"
