#!/bin/bash
########################################################################
# MuGLIn - MuGLIn GNU/Linux Installation		                       #
#                                                                      #
# Copyright (C) 2010 Jakob Gurnhofer <jakob.gurnhofer@gmail.com>       #
# Copyricht (C) 2010 Srdjan Markovic <smark2ki@htl.moedling.at>        #
#                                                                      #
# This file is part of MuGLIn source code.                             #
#                                                                      #
# MuGLIn 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 3 of the License, or    #
# (at your option) any later version.                                  #
#                                                                      #
# MuGLIn 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 MuGLIn. If not, see <http://www.gnu.org/licenses/>.       #
########################################################################

. /etc/muglin/base.conf
. /usr/local/lib/muglin/muglin.d/libmuglin

OSDIR="/usr/local/lib/muglin/image/os_scripts/"
MODDIR="/usr/local/lib/muglin/image/postinst/"

# a <name> - image name
# c <comment> - image comment
# o <os> - os to install
# i <comma separated list> - include post install hooks
# t <file> - file to export to
# s <os params>
# p - php mode
# m - import
# e - export

while getopts emps:n:c:o:i:t: OPTION;do
	case "$OPTION" in
		n)
			#if [[ "$(echo $OPTARG | grep -e '^[[:alnum:]_]*$')" == "" ]]; then
			#	echo "\"$OPTARG\" contains invalid characaters, aborting!"
			#	exit -1
			#fi
			checkimagename "$OPTARG"
			NAME="$OPTARG"
		;;
		c)
			if [[ "`echo "$OPTARG" | egrep '^\-'`" != "" ]]; then echo "Comment must not start with \"-\" (maybe missing argument?), aborting!"; exit -1; fi
			COMMENT="$OPTARG"
		;;
		o)
			if [[ ! -x $OSDIR/"$OPTARG" ]]; then echo "Could not find OS installation: \"$OPTARG\". Aborting!"; exit -1; fi
			OS="$OSDIR"/"$OPTARG"
		;;
		p)
			PHP=1
		;;
		i)
			POSTS=$(echo "$OPTARG" | sed 's/,/ /g')
		;;
		t)
			tFILE=$(readlink -f "$OPTARG")
			if [[ -e "$1" ]]; then
				echo "File \""$OPTARG"\" already exists. Overwrite? (y/n)"
				read overw
				if [[ "$overw" == "y" ]]; then
					rm $tFILE
				fi
			fi
			FILE=$tFILE
		;;
		e)
			setcmd export
		;;
		m)
			setcmd import
		;;
		s)
			ARGOS="$OPTARG"
		;;
		\?)
			echo "Unknown argument: \"$1\". Aborting!"
			exit -1
		;;
		:)
			echo "Option $OPTARG requires an argument. Aborting!"
			exit -1
		;;
	esac
done
  
if [[ "$NAME" == "" ]]; then
	echo "Missing -name. Aborting"
	exit -1
fi
if [[ "$OS" == "" ]]; then
	echo "Missing -os. Aborting"
	exit -1
fi
case "$CMD" in
	export)
		if [[ "$FILE" == "" ]]; then
			echo "Please provide -t <file>. Aborting"
			exit -1
		fi
	;;
	import):;;
	*)
		echo "Please provide -export or -import (XOR). Aborting"
		exit -1
	;;
esac

echo -n ">Preparing..."
gen_name(){
	TEMPDIR=$(pwgen 4 1)
	echo $IMG_PATH/$TEMPDIR
}

# where the image gets installed
TDIR=$(gen_name)
# where the image gets compressed
IDIR=$(gen_name)
until [[ ! -d $TDIR ]]; do
	TDIR=$(gen_name)
done
until [[ ! -d $IDIR ]]; do
	IDIR=$(gen_name)
done
mkdir $TDIR
mkdir $IDIR
echo "done"

echo -n ">Installing..."
iift=$($OS --dir $TDIR $ARGOS)
echo "done"

echo -n ">Adding post-installation modules (default: "
mkdir $TDIR/post.bin
mkdir $IDIR/post.bin
DEFPOST=$(grep 'DEFPOST=' $iift | sed -e 's/[(DEFPOST)=;"]//g')
# conditional copy of module
cond_copy_mod(){
if [[ "$(echo $2 | cut -d":" -f2)" == "1" ]]; then
  ln -s $MODDIR/server/$1.* $IDIR/post.bin/
fi
if [[ "$(echo $2 | cut -d":" -f3)" == "1" ]]; then
  cp -a $MODDIR/client/$1.* $TDIR/post.bin/
fi
}
while read line; do
  mod=$(echo $line | cut -d":" -f1);
  if [[ "$DEFPOST" =~ "$mod" ]]; then
    cond_copy_mod "$mod" "$line";
  elif [[ "$POSTS" =~ "$mod" ]]; then
    echo post; cond_copy_mod "$mod" "$line"
  else
    continue;
  fi;
done < /usr/local/lib/muglin/image/postinst/modules.list
echo -n "done, custom: "
# client-side post-inst stuff...
chmod +x $TDIR/post.bin
chmod +x $TDIR/post.bin
echo "done)"

echo -n ">Compressing..."
tar czf $IDIR/image.tgz -C $TDIR ./
ret=$?
if [[ "$ret" == "0" ]]; then echo "done"; else echo "failed (Tar exited with $ret)"; exit $ret; fi

# remove the temporary dirs - part one :)
rm -rf $TDIR

echo -n ">Writing image.iif..."
iif="$IDIR/image.iif"
USER=$(whoami)
echo "Name=$NAME" >> $iif
echo "Comment=$COMMENT" >> $iif
echo "Creator=$USER" >> $iif
if [[ -e $iift ]]; then
  grep 'Arch=' $iift >> $iif
  grep 'Type=' $iift >> $iif
fi
echo "[ChangeLog]" >> $iif
echo "[EndChangeLog]" >> $iif
/usr/local/lib/muglin/add_chlog_entry -php "$iif" $USER "Image created from: $OS"
echo "[Description]" >> $iif
echo "[EndDescription]" >> $iif
echo "Please enter a description now."
sleep 3
. /usr/local/lib/muglin/edit_desc
echo -n "done"

partfile=$IDIR/partitions
cat << PARTITIONSF
# Template
Disk:sda
1:p:100:82:ext2:/boot:b:
2:p:50:83:swap:::
3:p:*:82:ext3:/::-j

# Template end. Notice:
# 1) Please delete all comments (lines starting with #)
# 2) An empty line separates disk-entries
# 3) File MUST end with an new line!
PARTITIONSF > $partfile
echo ">You have to edit the partitions file now."
vim $partfile

case $CMD in
	import)
		. $iift
		echo -n ">Importing \"$NAME\"..."
		IID=$(mysql -u$MYS_USER -p$MYS_PASS -D$MYS_DB -B --skip-column-names -e"SELECT IID FROM Images WHERE Name = '$NAME';")
		if [[ "$IID" != "" ]]; then
			echo "An image named \"$NAME\" already exists (IID: $IID). Importing aborted"
			exit -3
		fi
		NDIR="$IMG_PATH/$(echo $NAME | sed 's/ /_/g')/"
		mv $(readlink -f $IDIR) $NDIR
		mysql -u$MYS_USER -p$MYS_PASS -D$MYS_DB -B --skip-column-names -e"INSERT INTO Images (Name,Comment,Path,Enabled,Architectur,Type) VALUES ('$NAME','$COMMENT','$NDIR',0,'$Arch',1);"
		echo "done"
	;;
	export)
		echo -n ">Exporting \"$NAME\""
		cd $IDIR
		zip -r $FILE ./
		cd $OLDPWD
		echo "done"
		rm -rfthx $IDIR
	;;
esac
rm $iift



# Root-Password = 123..abc

# /tmp/{iface,mount,unattend.post}

# iface:
# ethX

# mount:
# -t ext3 /dev/sda1 /target/boot
# -t swap /dev/sda2 none
# -t ext3 /dev/sda3 /target/

# unattend.post:
# SYS_HOSTNAME=Testhost
# SYS_MIRROR=http://archive.ubuntu.com/ubuntu
# SYS_DOMAIN=gurn.local
# 
