#!/bin/sh
#
# Frugal is a tiny tool to handle SliTaz frugal installation.
#
# Copyright (C) 2013-2015 SliTaz GNU/Linux - BSD License
#
# Author: Christophe Lincoln <pankso@slitaz.org>
#

. /lib/libtaz.sh

[ "$root" ] || root="/boot/frugal"


# NOTES:
#	Have a --web option to dl ISO ?
#	Auto configure GRUB ?
#


# Internationalization

export TEXTDOMAIN='slitaz-tools'


#
# Functions
#


# Small help and usage.

usage() {
	name=$(basename $0)
	cat << EOT

$(boldify $(_n 'Usage:')) $name [iso|command] [--options]

$(_n 'SliTaz frugal installation')

$(boldify $(_n 'Commands:'))
  info        $(_n 'Display install path and size stats')
  clean       $(_n 'Remove all frugal files')
  grub-ex     $(_n 'Show GRUB configuration example')

$(boldify $(_n 'Options:'))
  --root=     $(_n 'Set root installation path')
  --debug     $(_n 'Display some useful debug information')

$(boldify $(_n 'Examples:'))
  $name slitaz-rolling.iso
  $name slitaz-5.0.iso --root=/boot/frugal

EOT
}


# GRUB config example.

grub_example() {
	cat <<EOT
title SliTaz GNU/Linux (frugal)
root (hd0,0)
kernel /boot/frugal/bzImage root=/dev/null lang=en kmap=us
initrd /boot/frugal/rootfs.gz
EOT
}


#
# Commands
#

case "$1" in
	"") usage ;;
	info)
		title 'Frugal info'

		# First check if we are running in frugal mode
		if fgrep -q 'root=/dev/null' /proc/cmdline; then
			_ 'Frugal system running detected'
			footer; exit 0
		fi
		_n 'Installation directory:'; indent 30 $(colorize 36 "$root")
		_n 'Kernel size:'
		if [ -f "${root}/bzImage" ]; then
			indent 30 $(du -sh ${root}/bzImage | awk '{print $1}')
		else
			indent 30 $(boldify 'N/A')
		fi
		_n 'Rootfs size:'
		if [ -f "${root}/rootfs.gz" ]; then
			indent 30 $(du -sh ${root}/rootfs.gz | awk '{print $1}')
		else
			indent 30 $(boldify 'N/A')
		fi
		footer ;;
	clean)
		check_root
		_n 'Cleaning:'; echo " $root"
		rm -rf ${root}/* ;;
	grub-ex)
		title 'GRUB config example'
		grub_example
		footer ;;
	*)
		iso="$1"
		loop="/tmp/frugal-$$"
		check_root
		title 'SliTaz Frugal'
		if [ ! -f "$iso" ]; then
			_n 'Unable to find ISO image:'; colorize 31 " $iso"
			newline; return 1
		fi
		mkdir -p ${root}
		debug "$iso $root"
		_n 'Mounting ISO image...'
		mkdir -p ${loop}
		mount -o loop "$iso" ${loop} 2>/dev/null
		status

		_n 'Installing the Kernel...'
		cp -a ${loop}/boot/bzImage ${root}
		status

		_n 'Installing the root filesystem...'
		if [ -f ${loop}/boot/rootfs1.gz ]; then
			cd ${loop}/boot
			cat $(ls -r rootfs*.gz) > ${root}/rootfs.gz
			cd - >/dev/null
		else
			cp -a ${loop}/boot/rootfs.gz ${root}
		fi
		status

		# Umount the loop device
		_n 'Unmounting ISO image...'
		sleep 1
		umount ${loop} && rm -rf ${loop}
		status

		footer ;;
esac

exit 0
