#!/bin/bash

PATH=$PATH:/usr/local/lib/inx
. inx_essentials
maybe_switch

if ! grep -q casper /proc/cmdline ; then
    white ; clear
    echo -e "\n  This doesn't look like a live session.
  Currently inxusb can only be run from a live INX session, sorry.
  Exiting...\n"
    sleep 5
    unbold
    exit
fi

bblack ; clear ; echo
fig-col
figlet "  INXUSB"
info-col
echo -e "\n\n  This script makes a bootable INX system for USB \"sticks\"
  It creates a partition labelled \"INX\" and a partition labelled \"casper-rw\".
  The INX partition is 250 MB, and the casper-rw partition uses the rest of the drive.
  
  You probably want to use a USB device of at least 512 MB - 1 Gig or more is better.
  
  Obviously, plug in the device that you want to format as an INX bootable USB :-)
  You will see some text showing that the device is recognised - just go ahead
  if you want to create your \"persistent\" bootable system on the device.
  
  Be careful to select the right device! You will be given warnings and a chance to
  abort the process, but you do not want to accidentally wipe your hard drive ;-)\n"
  
head-col
echo -e "\n  Press <enter> to continue, any other key to exit.\n"
unbold
read -s -n 1
if [ "$REPLY" != ""  ] ; then echo ; exit ; fi


# Insert pretty asterisks progress feedback function/code ;-)
pretty_asterisks ()
{
    bold ; yellow
    while test $(pidof $THIS)
      do
        printf ' *'
        sleep .5
      done
    unbold      
}
	# Check if we are running as root: else nothing will happen...

	if [ $(id -u) -ne 0 ] ; then
        bold ; bred ; yellow

echo -e "\nThis bootable USB creator must be run as root.

You are running it as $USER.

Please run \" sudo $0 \"

Exiting ...\n"                      

        unbold
	sleep 5
        exit  1
	fi
	
# Mount device for this - check /mnt first?
if grep -q /mnt /etc/mtab ; then
    echo -e "\n  Your /mnt directory appears to be in use.
  Please unmount /mnt before running this USB creator script -
  the script uses it ...\n"
    sleep 5
    exit 1
fi

# Check if we are only looking at one drive - most likely hdd?
if [ "$(fdisk -l | grep ^Disk | grep -v identifier | wc -l)" = "1" ] ; then
    bold ; yellow
    echo -e "\n  Hmm - fdisk sees only one drive, probably your hard drive?
  Is your USB device plugged in? (y/n)\n"
    read
    if ! [ "$REPLY" = "y" -o "$REPLY" = "Y" ] ; then
        unbold
        exit
    fi
fi

INX=250 # Add question for this value?

choose_device ()
{
bold ; green
echo -e "\n  This is fdisk's idea of your devices.
  You are looking for USB devices, which normally will
  appear as /dev/sdb, /dev/sdc and so on. Make sure you 
  choose the right device, or you might wipe out all the 
  data on your hard drive! You will get a chance to confirm.\n"
bold ; yellow
fdisk -l | grep ^Disk | grep -v identifier
bold ; green
echo -e "\n  Type the device name for your usb stick (for example, /dev/sdb)"
echo -e "  Don't type the partition number, just the device name.\n"

}

device_check ()
{
unbold
read USB
echo

# Check up

if echo $USB | grep -q '[0-9]' ; then
    bold ; yellow
    echo -e "\n  Umm... *without* the partition number, please...
    Try again.\n"
    device_check
elif [ "$USB" = "" -o "$USB" = "." ] ; then
    bold ; yellow
    echo -e "\n  Umm, that doesn't look possible. Try again?\n"
    device_check
elif ! ls -l $USB > /dev/null ; then
    bold ; yellow
    echo -e "\n  That device doesn't seem to exist - please try again.\n"
    device_check
fi

}

be_sure ()
{
clear
bold ; green
echo -e "\n  You have chosen ${USB}. Fdisk shows this as:\n"
unbold
printf "  " ; fdisk -l $USB
bold ; yellow
echo -e "\n  Please be sure - you will lose any existing data on ${USB}. 
  Are you sure this is the right device for your USB? (enter \"yes\", if so).\n"
unbold
read 

if [ "$REPLY" = "no" ] ; then
    bold ; green
    echo -e "\n  OK - type q to quit, or <enter> to try again ...\n"
    unbold
    read -s -n 1
    if [ "$REPLY" = "q" -o "$REPLY" = "Q" ] ; then unbold ; exit ; fi	
    exec $0
elif [ "$REPLY" != "yes" ] ; then
    bold ; yellow
    echo -e "\n  Please type yes or no. Trying again...\n"
    sleep 3
    be_sure
fi    
}

choose_device
device_check
be_sure


# Unmount if mounted...
if grep -q $USB /etc/mtab ; then umount ${USB}* > /dev/null 2>&1 ; fi 

# fdisk -l $USB | grep 'Disk /dev' | awk '{print $3,$4}'

# read # Check disc size - warn if less than 512 MB or so, with alternative for 256 MB ?

sfdisk -uM $USB << EOF
,$INX,83,*
,,83
EOF

# Make file systems
# mkfs is more verbose but the second partition mounts too fast?
bold ; green
echo -e "\nMaking file systems... ${USB}1 labelled 'INX', ${USB}2 labelled 'casper-rw'.\n"
unbold
# Apparently usb auto-mount is fearsomely efficient...
umount ${USB}* > /dev/null 2>&1

#mkfs.ext2 -L INX ${USB}1
#mkfs.ext2 -L casper-rw ${USB}2
THIS=parted
parted -s ${USB} "mkfs 1 ext2" & pretty_asterisks
umount ${USB}* > /dev/null 2>&1
parted -s ${USB} "mkfs 2 ext2" & pretty_asterisks

bold ; green
echo -e "\nMaking partition labels ...\n"
unbold
THIS=e2label
e2label ${USB}1 INX & pretty_asterisks
e2label ${USB}2 casper-rw & pretty_asterisks

bold ; green
echo -e "\nChecking file systems ...\n"
unbold
# *sigh* every file system made gets auto mounted by usbmount immediately, again...
umount ${USB}1 > /dev/null 2>&1
fsck.ext2 ${USB}1 
umount ${USB}2 > /dev/null 2>&1
fsck.ext2 ${USB}2 

# Grub stuff...
bold ; green
echo -e "\nInstalling the grub bootloader...\n"
unbold

mount ${USB}1 /mnt
mkdir -p /mnt/boot/grub
echo "(hd0) $USB" > /mnt/boot/grub/device.map
# Boot message, menu.lst
cat << EOF >> /mnt/boot/grub/bootmessage

Loading kernel and initrd ...

This can take some time - please wait ...

EOF
# Edit menu, UUID, use variables instead of "INX 1.14" etc.
# UUID is safer here since the device name is not static...
PARTITION_UUID_1=$(vol_id --uuid ${USB}1)


# Check if this is a live INX session ... Need alternative for non-INX installs
if grep -q INX /etc/issue.net ; then
    TITLE_ID=$(cat /etc/issue.net)
else
    TITLE_ID=INX
fi    

cat << EOMENU >> /mnt/boot/grub/menu.lst
default 0
timeout 25
color yellow/green white/green

title $TITLE_ID 1024x768 (Persistent Mode)
root (hd0,0)
cat /boot/grub/bootmessage
kernel /casper/vmlinuz root=UUID=$PARTITION_UUID_1 boot=casper ro vga=791 persistent
initrd /casper/initrd.gz

title $TITLE_ID 1024x768 (No session persistence)
root (hd0,0)
cat /boot/grub/bootmessage 
kernel /casper/vmlinuz root=UUID=$PARTITION_UUID_1  boot=casper ro vga=791
initrd /casper/initrd.gz

title $TITLE_ID 1024x768 (Loaded to RAM - no persistence)
root (hd0,0)
cat /boot/grub/bootmessage
kernel /casper/vmlinuz root=UUID=$PARTITION_UUID_1 boot=casper ro vga=791 toram
initrd /casper/initrd.gz

title $TITLE_ID 800x600  (Persistent Mode)
root (hd0,0)
cat /boot/grub/bootmessage
kernel /casper/vmlinuz root=UUID=$PARTITION_UUID_1 boot=casper ro vga=788 persistent
initrd /casper/initrd.gz

title $TITLE_ID 800x600  (No session persistence)
root (hd0,0)
cat /boot/grub/bootmessage
kernel /casper/vmlinuz root=UUID=$PARTITION_UUID_1  boot=casper ro vga=788
initrd /casper/initrd.gz

title $TITLE_ID 800x600  (Loaded to RAM - no persistence)
root (hd0,0)
cat /boot/grub/bootmessage
kernel /casper/vmlinuz root=UUID=$PARTITION_UUID_1 boot=casper ro vga=788 toram
initrd /casper/initrd.gz

title Netinxtaller Stage 1 (Ubuntu 'cli' Net Install)
root (hd0,0)
cat /boot/grub/bootmessage
kernel /netinxtaller/linux root=UUID=$PARTITION_UUID_1 tasks=standard pkgsel/language-pack-patterns=pkgsel/install-language-support=false vga=normal
initrd /netinxtaller/initrd.gz
EOMENU

grub-install --no-floppy --root-directory=/mnt $USB

# Copy casper - insert pretty asterisks... ;-)
# For now, assuming live session...
bold ; green
echo -e "\nCopying INX system to ${USB}, partition label INX... Please wait...\n"
THIS=cp
cp -a /cdrom/casper /mnt/ & pretty_asterisks
if [ -d /cdrom/netinxtaller ] ; then
    THIS=cp
    cp -a /cdrom/netinxtaller /mnt/ & pretty_asterisks
fi   
bold ; green
echo -e "\n\nUnmounting ...\n"
umount /mnt

bold ; white
echo -e "\nINX system copied to ${USB}, partition label INX. Your INX USB device should now be bootable!\n"
unbold
sleep 4
exit
