#!/bin/bash
# kiwi-ltsp - Part of KIWI-LTSP as created by CyberOrg
#
# Copyright (c) 2012 CyberOrg
# 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.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
#
# Authors:		Jigish Gohil <cyberorg@cyberorg.info>
#			Magnus Boman <captain.magnus@gmail.com>
#			Shrenik Bhura <shrenik.bhura@intelliant.net>
#			Alex Savin <alexqwesa@opensuse.org>
#
# Version	Date		Changes
# 0.1.1		2007-08-25	Initial release
# 0.1.2		2007-08-27	Made the script modular with functions
# 0.1.3		2007-08-27	DHCP server setup '-d', complete server '-s'
# 0.1.4		2007-09-09	Added setup_tftpserver. Changed modify_hosts to run before building image
# 0.1.5		2007-09-10	Move location to /usr/sbin. Search for config file in /etc first and if not there, current directory
# 0.1.6		2007-09-24	Added -l1 switch
# 0.1.7		2008-03-16	Major overhaul, add -e, remove -a, make it l, l1 and l2 for image creation instead
# 0.2.0		2009-04-08	Added support for network booting FAT client and scanner configuration
# 0.2.1		2010-08-28	Added support for manage images, CONFIG_BLACKLIST, 
#						automatic setup NBD service( '-nbd' ), added '--intro', '--list-profiles'
# 0.2.2		2010-11-22	Reworked code related --test and CONFIG_BLACKLIST
# 0.2.3		2011-03-24	Added --clone, --import, --export
# 0.2.4		2011-08-28	Added --update-conf, --update-files, --remove-profile , --upgrade-image and --chroot 
# 0.2.5		2012-08-23	Added --export-to-rpm
# 0.2.6		2013-07-22	Added --test-in-vm
#======================================
# Initialize log file variable
#--------------------------------------
KIWI_LTSP_LOG=`mktemp /tmp/kiwi-ltsp-XXXXXXXXXX.log`
#======================================
# Load configs
#--------------------------------------
if  [[ -f /etc/sysconfig/kiwi-ltsp ]] ; then
	KIWI_LTSP_CONF_FILE="/etc/sysconfig/kiwi-ltsp"
	if  [[ -r /etc/sysconfig/kiwi-ltsp ]] ; then
		. $KIWI_LTSP_CONF_FILE
	else
		# This is workaround to allow user to read this file 
		KL_CONF_TEMP="`mktemp /tmp/kiwi-ltsp-sysconfig-XXXXXXXXX`"
		sudo cat $KIWI_LTSP_CONF_FILE > $KL_CONF_TEMP
		. $KL_CONF_TEMP
		rm $KL_CONF_TEMP
	fi
elif . ./kiwi-ltsp 2>/dev/null; then
	KIWI_LTSP_CONF_FILE="`pwd`/kiwi-ltsp"
else
	echo "Could not find config file (kiwi-ltsp) in /etc/sysconfig or `pwd`"
	exit 1
fi
#======================================
# Load shared library
#--------------------------------------
if [[ -L "$0" || -L `type -p $0` ]] ; then 
	KL_LINK="`type -p $0`"
	KL_WRAPPER="`readlink -f "$KL_LINK"`"
	KIWI_INCLUDE_NEW="`dirname "$KL_WRAPPER"`"
fi
# TODO: rename KIWI_INCLUDE to KIWI_LTSP_WORKDIR (or INSTALLDIR)
if . $KIWI_INCLUDE_NEW/kiwi-ltsp-functions.sh ; then
	KIWI_INCLUDE="$KIWI_INCLUDE_NEW"
elif . ./kiwi-ltsp-functions.sh ; then
	KIWI_INCLUDE="`pwd`"
elif ! . $KIWI_INCLUDE/kiwi-ltsp-functions.sh ; then
	echo "Could not find $KIWI_INCLUDE/kiwi-ltsp-functions.sh"
	echo "Check KIWI_INCLUDE variable in /etc/sysconfig/kiwi-ltsp file"
	echo "it standart value: /usr/share/kiwi-ltsp/ , current value: $KIWI_INCLUDE"
	exit 1
fi
#======================================
# Check variables on script kiwi-ltsp-functions.sh load
#--------------------------------------
check_variables
#======================================
# Check to make we are running as root (if --test not used)
#--------------------------------------
is_user_root
#======================================
# Log start
#--------------------------------------
KIWI_MANUAL_TASKS=`mktemp /tmp/manual_tasks-XXXXXXXXXX.txt`
log "====== Starting `date "+%Y.%m.%d"`======"
log "KIWI_LTSP dir: $KIWI_INCLUDE"
log "Config file: $KIWI_LTSP_CONF_FILE"
#======================================
# Check architecture
#--------------------------------------
check_architecture
#======================================
# Preparse script parameters
#--------------------------------------
if [ x"$1" = x"" ]; then
	need_help
	exit 0
fi
if [[ -n `echo " $@ " | grep -- " --test "` ]] ; then
	export TESTRUN=1
fi

while [[ -n "$1" ]]
	do
	case "$1" in
		NAME=*)
			LTSP_IMG_NAME="${1#NAME=}" # TODO: mark this as obsolete
			;;
		--list-profiles)
			echo -e "\n                 List of available image profiles:"
			echo "==========================================================================="
			echo $LTSP_PROFILES | tr '[:space:]' ' '
			echo -e "\nEdit LTSP_PROFILES variable in /etc/sysconfig/kiwi-ltsp to add new images."
			echo -e "\n           List of available default image profiles:"
			echo "==========================================================================="
			ls_default_profile
			exit 0
			;;
		--test-in-vm)
			shift
			test_in_vm $@
			exit 1
			;;
		--test)
			:
			;;
		--debug)
			LTSP_DEBUG=1
			;;
		--boot-menu|--update-conf|--update-files)
			if [[ -z $RUNPARAM ]] ; then
				RUNPARAM_CUTTED="${1#--}"
				RUNPARAM="$1"
			fi
			;;
		--chroot|--remove-profile|--export|--upgrade-image|--unpack-image)
			if [[ -z $2 ]] ; then
				echo "Error: Required parameter is missed" 
				need_help
				exit 1
			fi
			;;&
		--chroot)			enter_chroot   $2	;exit 0 ;;
		--remove-profile)	remove_profile $2	;exit 0 ;;
		--export)			export_profile $2	;exit 0 ;;
		--unpack-image)		unpack_image   $2	;exit 0 ;;
		--intro)			show_intro			;exit 0 ;;
		--upgrade-image)
			shift
			upgrade_kiwi_ltsp $@
			exit 0
			;;
		--clone|--import|--export-to-rpm)
			if [[ -z $3 ]] ; then
				echo "Error: Required parameter is missed" 
				need_help
				exit 1
			fi
			shift
			;;&
		--clone)			clone_profile  $1 $2 	;exit 0 ;;
		--export-to-rpm)	export_to_rpm  $@		;exit 0 ;;
		--import)			import_profile $1 $2	;exit 0 ;;
		--*|-h|-\?) 
			need_help
			exit 1
			;;
		-*)
			if [[ -z $RUNPARAM ]] ; then
				RUNPARAM_CUTTED="${1#-}"
				RUNPARAM="$1"
			fi
			;;
		*)
			test_Runparam "l l1 l2 ln n n1 n2 s i"
			if [[ $? == 0 ]] ;then 
				LTSP_IMG_NAME="$1"
			else
				echo "Error: Unknown option $1"
				exit 1
			fi
			;;
	esac
	shift
done
#======================================
# Create dir with configs files which will be changed
#--------------------------------------
create_test_dir  # TODO: don't create backup if we just build images
#======================================
# Detect host distro name
#--------------------------------------
detect_host_distro
#======================================
# Check obsoletes variables
#--------------------------------------
check_obsoletes_variables
#======================================
# Load required image profile
#--------------------------------------
load_kiwi_profile    # According to $LTSP_IMG_NAME, it made changes in image specific variables
#======================================
# Parse script parameters and run functions
#--------------------------------------
test_Runparam "s c d t e k boot-menu update-conf nbd update-files"
if [[ $? == 0 ]] ;then 
	pre_check
fi

test_Runparam "s c d t e k boot-menu update-conf l1 l ln"
if [[ $? == 0 ]] ;then 
	init_network_variables # TODO: don't run for "k boot-menu update-conf l1 l ln"
fi

test_Runparam "b p s"
if [[ $? == 0 ]] ;then 
	backup_config
fi

test_Runparam "p s"
if [[ $? == 0 ]] ;then 
	pre_check_packages
fi

test_Runparam "l1 l c s ln"
if [[ $? == 0 ]] ;then 
	kiwi_ltsp_setup_sshkeys
	modify_lts
fi

test_Runparam "k"
if [[ $? == 0 ]] ;then 
	kiwi_ltsp_setup_sshkeys
fi

test_Runparam "s l l1 ln"
if [[ $? == 0 ]] ;then 
	copy_config
fi

test_Runparam "l1 l s ln" 
if [[ $? == 0 ]] ;then 
	run_kiwi_ltsp1
fi

test_Runparam "l2 l s ln"
if [[ $? == 0 ]] ;then 
	run_kiwi_ltsp2
fi

test_Runparam "n n1 s ln"
if [[ $? == 0 ]] ;then 
	run_kiwi_netboot_phase1
fi

test_Runparam "n n2 s ln"
if [[ $? == 0 ]] ;then 
	run_kiwi_netboot_phase2
fi

test_Runparam "d s c"
if [[ $? == 0 ]] ;then
	if [[ $USE_DNSMASQ == "no" ]] ; then 
		setup_dhcpd_conf
	else
		. $KIWI_INCLUDE/setupdnsmasq.sh
		setup_dnsmasq
	fi
fi

test_Runparam "e"
if [[ $? == 0 ]] ;then 
	setup_exports 
fi

test_Runparam "t s c"
if [[ $? == 0 ]] ;then
	if [[ $USE_DNSMASQ == "no" ]] ; then 
		setup_tftpserver
	else
		log "tftp handled by dnsmasq, please run kiwi-ltsp -d or kiwi-ltsp -c to set it up if not done already"
	fi
	setup_pxe
fi

test_Runparam "nbd s c"
if [[ $? == 0 ]] ;then 
	setup_nbd
fi

test_Runparam "boot-menu s c"
if [[ $? == 0 ]] ;then 
	setup_pxe_boot_menu
fi

test_Runparam "s c"
if [[ $? == 0 ]] ;then 
	post_check
fi

test_Runparam "e nbd s c update-conf"
if [[ $? == 0 ]] ;then 
	configure_ltsp_scanner
	write_ltsp_config_files
fi

#======================================
# Move config files from test dir to root (except listed in CONFIG_BLACKLIST)
#--------------------------------------
restore_conf_from_testdir
#======================================
#fixup owner
#--------------------------------------
if [[ $DISTRO_HOST_NAME == "suse" ]] ; then
	if [[ $USE_DNSMASQ == "no" ]] ; then
		chown tftp:tftp $TFTPBOOTPATH -R &>/dev/null
	else
		chown dnsmasq $TFTPBOOTPATH -R
	fi
fi
#======================================
# Activate and restart all services which configs was changed
#--------------------------------------
activate_restart_services
#======================================
# Print list of manual tasks
#--------------------------------------
if [ -s $KIWI_MANUAL_TASKS ]; then
	echo "The following tasks need to be done manually:"
	cat $KIWI_MANUAL_TASKS
fi
log "====== Setup completed ======"
