#!/bin/bash

unset ISO
unset CHROOTDIR
MODE="FULL"

MNTDIR=`mktemp -d -t`
MODEFILE=`mktemp -t`

cleanup()
{
	umount -f $MNTDIR 2> /dev/null
	rmdir $MNTDIR 2> /dev/null
	rm -rf $MODEFILE
}

help_msg()
{
	echo "USAGE: salix-chroot-install -d [DESTDIR] -i [ISO]"
	echo ""
	echo "OPTIONS:"
	echo "   -d,  Path to the chroot destination directory"
	echo "   -i,  Path to a Salix iso"
	echo "   -h,  This help message"
}

error()
{
	echo "ERROR: $1" >&2
	cleanup
	exit 1
}

# Parse command line args
while getopts  ":hd:i:" flag
do
	# if switch is unknown or if asking for help
	if [ $flag = "?" ] || [ $flag = "h" ]; then
		help_msg
		exit 1
	fi
	if [ $flag = "d" ]; then
		if [ -d $OPTARG ]; then
			numfiles=`ls -A $OPTARG | wc -l`
			if [ $numfiles -eq 0 ]; then
				CHROOTDIR=$OPTARG
			else
				error "$OPTARG is not empty"
			fi
		else
			error "$OPTARG is not a directory"
		fi
	fi
	if [ $flag = "i" ]; then
		if [ -f $OPTARG ]; then
			echo $OPTARG | grep -q "\.iso$"
			retval=$?
			if [ $retval -eq 0 ]; then
				ISO=$OPTARG
			else
				error "$OPTARG is not an .iso file"
			fi
		else
			error "$OPTARG is not a file"
		fi
	fi
done

# Check if both chroot dir and iso are specified
if [ -z $CHROOTDIR ] && [ -z $ISO ]; then
	error "You need to specify the chroot directory and the iso to use"
fi

# Check for superuser
if [ "$UID" != "0" ]; then
	error "You don't have super powers!"
fi

# loop-mount the iso
mount -o loop $ISO $MNTDIR

if [ ! -d $MNTDIR/salix ]; then
	error "The iso file is not a Salix iso"
fi

# Select installation mode
dialog --title "SELECT INSTALLATION MODE" \
--no-cancel --menu \
"Please select the installation mode for the chroot" \
12 70 3 \
"FULL" "Install everything" \
"BASIC" "Install a minimal graphical environment" \
"CORE" "Install a minimal console system" 2> $MODEFILE
MODE=`cat $MODEFILE`

if [ "$MODE" = "FULL" ]; then
	INSTALLDIRS="aaa core basic full settings"
elif [ "$MODE" = "BASIC" ]; then
	INSTALLDIRS="aaa core basic settings"
else
	INSTALLDIRS="aaa core settings"
fi

# Install packages
# we don't need to install the kernel packages
for d in $INSTALLDIRS; do
	if [ -d $MNTDIR/salix/$d ]; then
		spkg -i --root=$CHROOTDIR --no-ldconfig --no-gtk-update-icon-cache \
			$MNTDIR/salix/$d/*.t[gx]z
	fi
done

# set default language to en_US
chroot $CHROOTDIR localesetup en_US.utf8

# determine if we're installing a 32bit or a 64bit system
BITS=$(chroot $CHROOTDIR getconf LONG_BIT)
if [ $BITS -eq 32 ] && \
	[ -f $CHROOTDIR/usr/bin/update-pango-querymodules ]; then
	sed -i \
		's/^host=$(uname -m)-slackware-linux$/host=i686-slackware-linux/' \
		$CHROOTDIR/usr/bin/update-pango-querymodules
fi

# update gtk/pango caches and other stuff
chroot $CHROOTDIR /usr/sbin/update-all

cleanup
