#! /bin/sh
# 
# Gtkdialog box for the mount command. Part of SliTaz tools.
#
VERSION=20081121

# Check if user is root.
check_root()
{
	if test $(id -u) != 0 ; then
		echo -e "
You must be root to run `basename $0`. Please type 'su' and 
root password to become super-user.\n"
		exit 0
	fi
}

# This function is used after each screen to contine or abort install.
check_retval()
{
	case $retval in
		1)
			rm -f /tmp/floppybox.grub.menu
			echo -e "\nVoluntary exit.\n" && exit 0 ;;
		255)
			rm -f /tmp/floppybox.grub.menu
			echo -e "ESC pressed.\n" && exit 0 ;;
	esac
}

select_floppy()
{
	DEVICE="$DIALOG --title \" Floppy device \" --backtitle \"Boot Floppy Creation\" --clear --extra-button --extra-label \"Format\" --colors --radiolist \"
Select boot device
\" 18 70 50"
	on=on
	for i in /sys/devices/platform/floppy.*/block:*; do
		[ -d $i ] || continue
		DEVICE="$DEVICE /dev/${i#*block:} 'Floppy in ${i#*block:}' $on"
		on=off
	done
	DEVICE="$DEVICE floppy \"cdrom image file boot.iso\" $on"
	DEVICE="$DEVICE cdrom \"floppy image file boot.fd\" off 2>&1 1>&3"
	exec 3>&1
	DEVICE=`eval $DEVICE`
	retval=$?
	exec 3>&-
	check_retval
	if [ "$retval" = "3" ]; then
		case "$DEVICE" in
		/dev/*) fdformat -n $DEVICE;;
		esac
    	fi
}

mkmenu()
{
if [ "$1" = "grub4dos" ]; then
	SAVEDEFAULT="save default"
	cat > /tmp/floppybox.grub.menu <<EOT
# grub4dos menu
default /default
EOT
else
	SAVEDEFAULT="savedefault"
	cat > /tmp/floppybox.grub.menu <<EOT
# grub menu
default saved
EOT
fi
cat >> /tmp/floppybox.grub.menu <<EOT
timeout 8
color yellow/brown light-green/black

EOT
entry=0
[ -f /boot/gpxe ] && entry=$(($entry + 1)) && cat >> /tmp/floppybox.grub.menu <<EOT
title gPXE (Boot from the Web, PXE/iSCSI/AoE support)
	kernel /boot/gpxe $(dd if=/boot/gpxe bs=1 skip=519 count=255 2>/dev/null | strings)

EOT
[ -f /usr/share/boot/btmgr -a -f /usr/share/boot/memdisk.lzma ] \
	&& entry=$(($entry + 1)) && cat >> /tmp/floppybox.grub.menu <<EOT
title Smart Boot Manager (text - boot floppy, hard disk or CD/DVD)
	kernel /boot/memdisk floppy c=80 h=2 s=18
	initrd /boot/btmgr.gz

EOT
[ -f /usr/share/boot/plop.gz -a -f /usr/share/boot/memdisk.lzma ] \
	&& entry=$(($entry + 1)) && cat >> /tmp/floppybox.grub.menu <<EOT
title Plop Boot Manager (graphic - boot floppy, hard disk, CD/DVD or USB)
	kernel /boot/memdisk floppy c=80 h=2 s=18
	initrd /boot/plop.gz

EOT
[ -f /usr/share/boot/etherboot ] && entry=$(($entry + 1)) && cat >> /tmp/floppybox.grub.menu <<EOT
title Etherboot (LAN boot, PXE or NBI)
	kernel /boot/etherboot

EOT
[ -f /usr/share/boot/memtest.lzma -a -f /usr/share/boot/memdisk.lzma ] \
&& entry=$(($entry + 1)) && cat >> /tmp/floppybox.grub.menu <<EOT
title Memtest86+ (Test system memory)
	kernel /boot/memdisk floppy c=80 h=2 s=18
	initrd /boot/memtest.gz

EOT
[ "$1" = "grub4dos" ] && entry=$(($entry + 3)) && cat >> /tmp/floppybox.grub.menu <<EOT
title Windows (scan ntldr)
	fallback $(($entry -3 + 1))
        find --set-root /ntldr
	chainloader /ntldr
	$SAVEDEFAULT --wait=2

title Windows (scan cmldr)
	fallback $(($entry -3 + 2))
        find --set-root /cmldr
        chainloader /cmldr
	$SAVEDEFAULT --wait=2

title Windows (scan io.sys)
	fallback $(($entry -3 + 3))
        find --set-root /io.sys
        chainloader /io.sys
	$SAVEDEFAULT --wait=2

EOT
entry=$(($entry + 3)) && cat >> /tmp/floppybox.grub.menu <<EOT
title Windows (example on /dev/hda1)
	rootnoverify (hd0,0)
	chainloader +1
	$SAVEDEFAULT

title Slitaz Frugal (example on /dev/hda1)
	root (hd0,0)
	kernel /boot/bzImage rw root=/dev/null vga=normal
	initrd /boot/rootfs.gz
	$SAVEDEFAULT

title Slitaz Installed (example on /dev/hda2)
	root (hd0,1)
	kernel /boot/bzImage ro root=/dev/hda2 vga=normal
	$SAVEDEFAULT

EOT
[ "$1" = "grub4dos" ] && entry=$(($entry + 1)) && cat >> /tmp/floppybox.grub.menu <<EOT
title Slitaz cdrom image (example on /dev/hda1, DEFRAGMENTED)
        map (hd0,0)/boot/slitaz-cooking.iso (hd1)
        map --hook
        kernel (hd1)/boot/bzImage rw root=/dev/null vga=normal
        initrd (hd1)/boot/rootfs.gz
	$SAVEDEFAULT

EOT
false && [ -f /usr/share/boot/grub.exe.lzma ] && entry=$(($entry + 1)) && cat >> /tmp/floppybox.grub.menu <<EOT
title Grub4Dos
	kernel /boot/grub/grub.exe --config-file="configfile (fd0)/boot/grub/menu4dos.lst"

EOT
}

install_grub()
{
	LOOP=""
	GRUB_DEV=${DEVICE#/dev/}
	GRUB_DEV=${GRUB_DEV%% *}
	case "$DEVICE" in
	floppy*)
		LOOP="-o loop"
		GRUB_DEV=fd0
		DEVICE=boot.fd
		dd if=/dev/zero of=$DEVICE bs=18k count=80;;
	esac
	grep -qs "^# $2 menu" /tmp/floppybox.grub.menu || mkmenu $2
	case "$DEVICE" in
	/dev/*|boot.fd)
		yes y | mke2fs $DEVICE
		mkdir /media/floppy
		mount $LOOP $DEVICE /media/floppy
		if [ "$2" = "grub4dos" ]; then
			mkdir -p /media/floppy/boot
			unlzma -c /usr/share/boot/grldr.lzma > /media/floppy/grldr
			cp $1/boot/* /media/floppy/boot 2> /dev/null
			cp /tmp/floppybox.grub.menu /media/floppy/menu.lst
			umount -d /media/floppy
			bootlace --floppy --sectors-per-track=18 --heads=2 \
				 --chs --ext2 $DEVICE
		else
			mkdir -p /media/floppy/boot/grub
			cp /usr/lib/grub/i386-pc/stage? /media/floppy/boot/grub
			cp -a $1/boot /media/floppy
			cp /tmp/floppybox.grub.menu /media/floppy/boot/grub/menu.lst
			grub-set-default --root-directory=/media/floppy 0
			echo "($GRUB_DEV) $(losetup | grep $DEVICE | cut -d: -f1)" > $1/device.map
			[ -n "$LOOP" ] && LOOP="--device-map=$1/device.map"
			grub $LOOP --batch <<EOT
root ($GRUB_DEV)
setup ($GRUB_DEV)
quit
EOT
			umount -d /media/floppy
		fi ;;
	cdrom*)
		mkdir -p $1/boot/grub 2> /dev/null
		cp /tmp/floppybox.grub.menu $1/boot/grub/menu.lst
		if [ "$2" = "grub4dos" ]; then
			unlzma -c /usr/share/boot/grldr.lzma > $1/boot/grub/grldr
			genisoimage -R -o boot.iso -b boot/grub/grldr \
				-c boot/boot.cat -no-emul-boot -boot-load-seg 0x1000 \
				-hide boot/boot.cat -input-charset iso8859-1 $1
		else
			cp /usr/lib/grub/i386-pc/stage2_eltorito $1/boot/grub
			genisoimage -R -o boot.iso -b boot/grub/stage2_eltorito \
				-c boot/boot.cat -no-emul-boot -boot-load-size 4 \
				-hide boot/boot.cat -input-charset iso8859-1 \
				-boot-info-table $1
		fi ;;
	esac
}

while true; do

if [ "$1" == "call" ]; then
	case "$2" in
	mkmenu) mkmenu $3;;
	install)
		DIR=/tmp/mkbootfloppy$$
		mkdir -p $DIR
		DEVICE=$4
		file=$5
		case "$3" in
		grub*)
			mkdir -p $DIR/boot/grub
			[ -f /usr/share/boot/btmgr -a -f /usr/share/boot/memdisk.lzma ] \
				&& cat /usr/share/boot/btmgr /dev/zero | \
				   dd bs=18k count=80 | gzip -9 > \
				   $DIR/boot/btmgr.gz \
				&& unlzma -c /usr/share/boot/memdisk.lzma > \
					$DIR/boot/memdisk
			[ -f /usr/share/boot/plop.gz -a \
			  -f /usr/share/boot/memdisk.lzma ] \
				&& zcat /usr/share/boot/plop.gz | \
				   cat - /dev/zero | dd bs=18k count=80 | \
				   gzip -9 > $DIR/boot/plop.gz \
				&& unlzma -c /usr/share/boot/memdisk.lzma > \
					$DIR/boot/memdisk
			[ -f /usr/share/boot/etherboot ] \
				&& cp /usr/share/boot/etherboot $DIR/boot
			[ -f /boot/gpxe ]\
				&& cp /boot/gpxe $DIR/boot
			[ -f /usr/share/boot/memtest.lzma -a \
			  -f /usr/share/boot/memdisk.lzma ] \
				&& unlzma -c /usr/share/boot/memtest.lzma | \
				   cat - /dev/zero | dd bs=18k count=80 | \
				   gzip -9 > $DIR/boot/memtest.gz \
				&& unlzma -c /usr/share/boot/memdisk.lzma > \
					$DIR/boot/memdisk
			install_grub $DIR $3
			;;
		*)
    			case "$file" in
    			*.lzma) action="unlzma -c";;
    			*.gz)   action="zcat";;
    			*)      action="cat";;
    			esac
			case "$DEVICE" in
			/dev/*) $action $file > $DEVICE;;
			flopp*) $action $file | cat - /dev/zero | \
						dd bs=18k count=80 > boot.fd;;
			cdrom*)
				mkdir -p $DIR/boot/grub
				case "$3" in
				btmgr|plop|memtest)
					$action $file | cat - /dev/zero | \
						dd bs=18k count=80 | \
						gzip -9 > $DIR/boot/$3.gz
					unlzma -c /usr/share/boot/memdisk.lzma \
						> $DIR/boot/memdisk
					cat > /tmp/floppybox.grub.menu << EOT
# grub menu
timeout 0
title $3
kernel /boot/memdisk floppy c=80 h=2 s=18
initrd /boot/$3.gz
EOT
					;;
				*)	$action $file > $DIR/boot/$3
					cat > /tmp/floppybox.grub.menu << EOT
# grub menu
timeout 0
title $3
kernel /boot/$3
EOT
					;;
				esac
				install_grub $DIR grub
				;;
			esac
			;;
		esac
		rm -rf $DIR
		;;
	get-plop)
		PLOP_URL="$(wget -O - http://www.plop.at/en/bootmanagerdl.html |\
			    grep plpbt | head -1 |\
			    sed 's|.*href=\(.*\) target.*|\1|')"
		VERSION="$(basename $PLOP_URL| sed 's/[^0-9\.]*\(.*\).zip/\1/')"
		mkdir -p /tmp/get-plop$$/plop-$VERSION/fs/$(dirname $3)
		wget -O - $PLOP_URL | unzip -p /dev/stdin '*/plpbt.img' | \
			gzip -9 > /tmp/get-plop$$/plop-$VERSION/fs/$3
		if [ -s /tmp/get-plop$$/plop-$VERSION/fs/$3 ]; then 
			cat > /tmp/get-plop$$/plop-$VERSION/receipt <<EOT
PACKAGE="plop"
VERSION="$VERSION"
CATEGORY="non-free"
SHORT_DESC="Plop boot manager."
WEB_SITE="http://www.plop.at/en/bootmanager.html"
EOT
			( cd /tmp/get-plop$$ ; tazpkg pack plop-$VERSION )
			tazpkg install /tmp/get-plop$$/plop-$VERSION.tazpkg
		fi
		rm -rf /tmp/get-plop$$
		;;
	*)	echo "Invalid command $0 $@" 1>&2
		exit 1;;
	esac
	exit 0
fi

if [ -z "$XAUTHORITY" ]; then

    : ${DIALOG=dialog}
    
    DEVICE=/dev/fd0
    while true; do
	exec 3>&1
	ID_SOURCE=`$DIALOG --title " Choose a boot floppy " \
		--backtitle "Boot Floppy Creation on $DEVICE" --clear \
		--extra-button --extra-label "Change floppy" \
		--yes-label "Install" \
		--no-label "Quit" \
		--colors --radiolist "
Create a floppy or a cdrom to boot a LiveCD in a PXE network...
May need a floppy disk in drive. Erase the whole floppy disk.
		" 18 70 50\
		SmartBtmgr	"Boot any partition or ATAPI CD-ROM." on \
		Plop		"Boot harddisk floppy CD/DVD or USB." off \
		Etherboot	"Replacement for proprietary PXE ROMs." off \
		gPXE		"Boot from http://boot.slitaz.org/" off \
		Memtest86+	"Memory failures detection tool." off \
		Grub4DOS	"Enhanced grub version supporting NTFS" off \
		Grub		"Boot loader with command shell." off  2>&1 1>&3`
	retval=$?
	exec 3>&-
	check_retval
	if [ "$retval" = "3" ]; then
		select_floppy
		continue;
	fi
	while read key file pkg; do
		[ "$key" = "$ID_SOURCE" ] || continue
		if [ ! -f "$file" ]; then
			$DIALOG --title " Install package " --colors \
				--backtitle "Boot Floppy Creation" --clear \
				--yes-label "Install" \
				--no-label "Quit" \
				--yesno "The package $pkg is not yet installed. Install it ?" 18 70
			retval=$?
			if [ "$pkg" = "plop" ]; then
				bootfloppybox call get-plop $file
			else
				tazpkg get-install $pkg
			fi
		fi
		bootfloppybox call install "$pkg" "$DEVICE" "$file"
		exit 0
	done <<EOT
SmartBtmgr /usr/share/boot/btmgr btmgr
Plop /usr/share/boot/plop.gz plop
Etherboot /usr/share/boot/etherboot etherboot
gPXE /boot/gpxe gpxe
Memtest86+ /usr/share/boot/memtest.lzma memtest
Grub4DOS /usr/share/boot/grldr.lzma grub4dos
Grub /usr/sbin/grub grub
EOT
    done
fi
#
# Describe gPXE arguments.
#
export HELP='
<window title="gPXE forced url" icon-name="gtk-floppy">
<vbox>
    <text use-markup="true">
    <label>"
<b>Web boot parameters</b>"
    </label>
  </text>
  <frame>
    <text wrap="true" width-chars="58" use-markup="true">
      <label>
"Without parameters (i.e. with an empty Boot URL) gPXE will perform a normal PXE boot: IP configuration with DHCP and download DHCP bootfile with TFTP.

You can override the DHCP bootfile with a Boot URL such as <i>tftp://192.168.0.1/pxe/pxeloader</i>, <i>http://mirror.slitaz.org/pxe/pxelinux.0</i>, or <i>x-tftm://192.168.0.201//lts/vmlinuz.ltsp</i>.

You can override IP  configuration too (useful without DHCP server), example: 
<i>ip=192.168.0.10/24 gw=192.168.0.1 dns=192.168.0.1 nodhcp url=http://mirror.slitaz.org/pxe/pxelinux.0</i>

The <i>nodhcp</i> keyword avoids dhcp timeouts and the <i>url=</i> keyword is optional when the url is the only one argument.
"
      </label>
    </text>
  </frame>
</vbox>
</window>
'
#
# Read/write floppy images
#
export FLOPPY_IMAGE='
<window title="Floppy image manager" icon-name="gtk-floppy">
  <vbox>
    <frame Floppy disk drive>
      <hbox>
        <text use-markup="true">
          <label>"<b>Device : </b>"</label>
        </text>
	<combobox>
          <variable>DEVICE</variable>'
for i in /sys/devices/platform/floppy.*/block:*; do
	[ -d $i ] || continue
	FLOPPY_IMAGE="$FLOPPY_IMAGE
	  <item>/dev/${i#*block:}</item>"
done
	FLOPPY_IMAGE="$FLOPPY_IMAGE
	</combobox>
        <button>
          <label>Format floppy</label>
          <input file icon=\"media-floppy\"></input>
	  <action>fdformat -n $DEVICE</action>
        </button>
      </hbox>
    </frame>
    <frame Floppy image file>
      <hbox>
        <text use-markup=\"true\">
          <label>\"<b>File : </b>\"</label>
        </text>
        <entry accept=\"filename\">
          <label>Select a floppy image</label>
          <variable>IMAGE</variable>
        </entry>
        <button>
          <input file stock=\"gtk-open\"></input>
          <action type=\"fileselect\">IMAGE</action>
        </button>
      </hbox>
    </frame>
    <hbox>
      <button>
        <input file icon=\"go-jump\"></input>
        <label>Write image to floppy</label>
        <action>dd if=\$IMAGE of=\$DEVICE</action>
      </button>
      <button>
        <input file icon=\"undo\"></input>
        <label>Get floppy image</label>
        <action>dd if=\$DEVICE of=\$IMAGE</action>
      </button>
      <button>
        <input file icon=\"gtk-close\"></input>
        <action type=\"closewindow\">FLOPPY_IMAGE</action>
      </button>
    </hbox>
  </vbox>
</window>
"
#
# Write bootfloppy image to floppy device.
#
BOOT_DIALOG='
<window title="bootfloppybox" icon-name="gtk-floppy">
  <vbox>
 
    <text use-markup="true">
      <label>
"
<b>SliTaz - Bootfloppybox</b>"
      </label>
    </text>
    <text wrap="false" width-chars="44" use-markup="true">
      <label>
"
Create a floppy or a cdrom to boot a LiveCD in a PXE network or WEB...
May need a floppy disk in drive. Erase the whole floppy disk.
"
      </label>
    </text>
  
    <frame Floppy disk drive>
      <hbox>
        <text use-markup="true">
          <label>"<b>Device : </b>"</label>
        </text>
	<combobox>
          <variable>DEVICE</variable>'
for i in /sys/devices/platform/floppy.*/block:*; do
	[ -d $i ] || continue
	BOOT_DIALOG="$BOOT_DIALOG 
	  <item>/dev/${i#*block:}</item>"
done
tmp='	  <item>cdrom image (boot.iso)</item>
	  <item>floppy image (boot.fd)</item>
	</combobox>
        <button>
          <label>Format floppy</label>
          <input file icon="media-floppy"></input>
	  <action>case "$DEVICE" in /dev/*) fdformat -n $DEVICE;; esac</action>
        </button>
      </hbox>
    </frame>
    <notebook labels="LiveCD|USB|PXE Network|WEB Network|Memory Test|Windows|Expert">
'  
BOOT_DIALOG="$BOOT_DIALOG$tmp"
while read name file pkg desc; do
    tmp="<frame $name>
      <hbox>
    <text wrap=\"true\" width-chars=\"44\" use-markup=\"true\">
      <label>
\"
$(echo -e $desc)
\"
      </label>
    </text>
      </hbox>
      <hbox>
"
  if [ -f $file ]; then
    if [ "$pkg" = "grub" -o "$pkg" = "grub4dos" ]; then
      tmp="$tmp
      <button>
        <label>Grub menu</label>
        <input file icon=\"accessories-text-editor\"></input>
	<action>bootfloppybox call mkmenu $pkg</action>
        <action type=\"lauch\">leafpad /tmp/floppybox.grub.menu</action>
      </button>
"
    elif [ "$pkg" = "etherboot" ]; then
      tmp="$tmp
      <button>
        <input file icon=\"browser\"></input>
	<label>Wiki</label>
	<action>firefox http://wiki.slitaz.org/doku.php?id=quickstart:pxe &</action>
      </button>
"
    elif [ "$pkg" = "gpxe" ]; then
      tmp="$tmp
      <text wrap=\"true\" use-markup=\"true\">
        <label> \"<b>Boot URL:</b>\" </label>
      </text>
      <entry>
	<default>$(dd if=$file bs=1 skip=519 count=255 2>/dev/null | strings)</default>
        <variable>URL</variable>
      </entry>
      </hbox>
      <hbox>
      <button>
        <input file icon=\"browser\"></input>
	<label>Wiki</label>
	<action>firefox http://wiki.slitaz.org/doku.php?id=quickstart:pxe &</action>
      </button>
      <button help>
	<action type=\"launch\">HELP</action>
      </button>
      <button>
        <label>Update</label>
        <input file icon=\"reload\"></input>
	<action>echo -n \"\$URL\" | cat - /dev/zero | dd conv=notrunc bs=1 count=255 seek=519 of=$file 2>/dev/null</action>
      </button>
"
    fi
    receipt=/var/lib/tazpkg/installed/$pkg/receipt
    if [ -f $receipt ]; then
      . $receipt
      tmp="$tmp
      <button>
        <input file icon=\"browser\"></input>
	<label>Web</label>
	<action>firefox $WEB_SITE &</action>
      </button>
"
    fi
    tmp="$tmp
      <button>
        <label>Write floppy</label>
        <input file icon=\"forward\"></input>
	<action>bootfloppybox call install \"$pkg\" \"\$DEVICE\" \"$file\"</action>
      </button>
      </hbox>
    </frame>
"
  else
    tmp2="tazpkg get-install $pkg --forced"
    [ "$pkg" = "plop" ] && tmp2="bootfloppybox call get-plop $file"
    tmp="$tmp
      <text wrap=\"true\" width-chars=\"34\" use-markup=\"true\">
        <label>
\"<i>The package <b>$pkg</b> is not yet installed</i>\"
        </label>
      </text>
      <button>
        <input file icon=\"go-jump\"></input>
	<label>Install</label>
	<action>[ -f /var/lib/tazpkg/packages.list ] || tazpkg recharge</action>
	<action>xterm -fa MiscFixed -fs 11 -bg gray93 -fg black -geometry 80x17 -title \"$pkg install\" -e \"$tmp2 ; sleep 2\"</action>
        <action type=\"exit\">restart</action>
      </button>
      </hbox>
    </frame>
"
  fi
  BOOT_DIALOG="$BOOT_DIALOG$tmp"
done <<EOT
SmartBtmgr /usr/share/boot/btmgr btmgr This OS independent Smart Boot Manager can boot any          partition or ATAPI CD-ROM.
Plop /usr/share/boot/plop.gz plop This non free Boot Manager can boot a floppy disk, hardisk, USB or CD/DVD. Hit Ctrl-ESC for text mode.
Etherboot /usr/share/boot/etherboot etherboot This network bootloader provides a replacement for proprietary PXE or NBI ROMs.
gPXE /boot/gpxe gpxe PXE / iSCSI / AoE network bootloader.
Memtest86+ /usr/share/boot/memtest.lzma memtest Memory failures detection tool.
Grub4DOS /usr/share/boot/grldr.lzma grub4dos Enhanced grub version supporting NTFS
Grub /usr/sbin/grub grub General purpose boot loader with command shell
EOT
tmp='
    </notebook>
    <hbox>
      <button>
        <input file icon="media-cdrom"></input>
	<label>Burn cdrom image</label>
	<action>burnbox</action>
      </button>
      <button>
        <input file icon="media-floppy"></input>
	<label>Manage floppy image</label>
	<action type="launch">FLOPPY_IMAGE</action>
      </button>
      <button>
        <input file icon="exit"></input>
	<label>Exit</label>
        <action type="exit">Exit</action>
      </button>
    </hbox>
  
  </vbox>
</window>
'
BOOT_DIALOG="$BOOT_DIALOG$tmp"
export BOOT_DIALOG

# Only root can create floppy.
check_root
gtkdialog --program=BOOT_DIALOG | grep -q 'EXIT="restart"' && continue
rm -f /tmp/floppybox.grub.menu
exit 0
done
