#!/bin/sh
# Vector Linux SETUP

vdir=$(dirname $0)
. $vdir/setup-functions

## Variables
MEDIA_DEV=""
MEDIA_TYPE=""
SWAP_DEVS=""
ROOT_DEV=""
ROOT_FS=""
HOME_DEV=""
HOME_FS=""
BULK_FILES=""

ROOT_MNT="/mnt/target"
HOME_MNT="/mnt/target/home"
LOOP_MNT="/mnt/source"

mkdir -p $LOOP_MNT
mkdir -p $ROOT_MNT

error() {
umount $HOME_MNT 2>/dev/null
umount $ROOT_MNT 2>/dev/null
umount $LOOP_MNT 2>/dev/null
echo
echo "ERROR! There was a problem!  Installation is not completed!"
echo
exit 
}

# Mount a device and look if there is a veclinux.bz2 
# on it
# $1 = the device
# $2 = type
search_media() {
    # umount for sure
    umount $LOOP_MNT 2>/dev/null
    DEV=$1
    TYPE=${2:+"-t $2"}
    dbug "mount $TYPE $DEV $LOOP_MNT" 
    if mount $TYPE $DEV $LOOP_MNT 2>> $flog; then
	if [ -r $LOOP_MNT/veclinux/veclinux.tar.bz2 ] ||
	   [ -r $LOOP_MNT/veclinux/veclinux.bz2 ]; then
    	    MEDIA_DEV=$DEV
	    dbug "FOUND" 
    	    return 0
	fi
	umount $LOOP_MNT
	dbug $(ls $LOOP_MNT/veclinux/*.bz2 2>&1)
    fi
    dbug "NOT FOUND"
    return 1
}

#########################################################################################
# SHOW information then FIND Install Media
# In the end of this process, Vector Linux media will be mounted on $LOOP_MNT
# or FAILED then EXIT

menuA() {
    TITLE="VECTOR LINUX INSTALL IT NOW"
    TEXT="\n
Here are our job list. We will begin as soon as you hit <OK>.\n
If you make mistake, you may step back by pressing [Esc] key.\n
Selecting <Cancel> will abort the process."

$DCMD --backtitle "$BACKTITLE" --title "$TITLE" --menu "$TEXT" 22 76 12 \
"MEDIA" "find and check Vector Linux media (CDROM)" \
"SWAP"   "select swap partition" \
"ROOT"   "select root partition" \
"HOME"   "select home partition" \
"BULK"   "select the bulk that you want to install" \
"INSTALL" "extract vector linux to the harddisk" \
"LILO" "configure LILO to boot Linux properly" \
"AUTOSETUP" "auto detect and configure hardware" \
"XWINDOW" "configure X-Window System" \
"NETWORK" "configure the network" \
"SOUND" "configure sound card" \
"USER" "Change root password and create a normal user" 

    status=$?
    [ $status != 0 ] && return $status

    TITLE="VECTOR LINUX INSTALL"
    # if /mnt/loop is already mounted, accept it 
    MEDIA_TYPE="Unknown"
    MEDIA_DEV=$(df | grep /mnt/loop)
    if [ $? = 0 ]; then
    	if [ -r $LOOP_MNT/veclinux/veclinux.tar.bz2 ] ||
	   [ -r $LOOP_MNT/veclinux/veclinux.bz2 ]; then
    	    MEDIA_DEV=$(echo $MEDIA_DEV | cut -f 1 -d ' ')
	    dbug "FOUND" 
    	    return 0
	fi
    fi    

    infobox "Finding media on Window partitions ..."
    MEDIA_TYPE="Windows HD"
    fdisk -l | grep FAT12 | cut -f 1 -d ' ' >/tmp/dev
    if [ $? = 0 ]; then
	for dev in `cat /tmp/dev`; do 
	    if search_media "$dev" "msdos" ; then
	        return 0
	    fi
	done
    fi

    fdisk -l | grep "FAT16" | cut -f 1 -d ' ' > /tmp/dev
    if [ $? = 0 ]; then
	for dev in `cat /tmp/dev`; do
	    if search_media "$dev" "vfat" ; then
	        return 0
	    fi
	done
    fi

    fdisk -l | grep "FAT16" | cut -f 1 -d ' ' > /tmp/dev
    if [ $? = 0 ]; then
	for dev in `cat /tmp/dev`; do
	    if search_media "$dev" "msdos" ; then
	        return 0
	    fi
	done
    fi

    fdisk -l | grep "FAT32" | cut -f 1 -d ' ' > /tmp/dev 
    if [ $? = 0 ]; then
	for dev in `cat /tmp/dev`; do
	    if search_media "$dev" "vfat" ; then
	        return 0
	    fi
	done
    fi

    infobox "Finding media on Linux partitions ..."
    MEDIA_TYPE="Linux HD"
    fdisk -l | grep -e "83 *Linux" | cut -f 1 -d ' ' > /tmp/dev
    if [ $? = 0 ]; then
	for dev in `cat /tmp/dev`; do
	    if search_media "$dev"  ; then
	        return 0
	    fi
	done
    fi

    infobox "Finding media on CD/DVD ..."
    MEDIA_TYPE="CD/DVD"
    dmesg | grep CD/DVD-ROM | cut -f 1 -d ':' | sed -n '1 p' > /tmp/dev
    if [ $? = 0 ]; then
	for j in `cat /tmp/dev`; do 
	    if search_media "/dev/$j" ; then
	        return 0
	    fi
	done
    fi

    # Funny, after several attempts, dmesg show me this 
    # hdc: ATAPI 52X CD-ROM drive, 120kB Cache, UDMA(33)
    dmesg | grep ATAPI | cut -f 1 -d ':' | sed -n '1 p' > /tmp/dev
    if [ $? = 0 ]; then
	for j in `cat /tmp/dev`; do 
	    if search_media "/dev/$j" ; then
	        return 0
	    fi
	done
    fi

    infobox "Finding media on SCSI devices ..."
    MEDIA_TYPE="SCSI"
    #well there weren't any ide devices so lets check for a scsi CD
    for i in 0 1 2 3 4 5 6 7; do
	if search_media /dev/scsi$i iso9660 ; then
	    $DCMD --backtitle "$BACKTITLE" --title "Okay found it" --msgbox \
"Well you rascal, had your Vector Linux CD on a SCSI drive.\n
Everything looks okay now so hit enter and we will continue." 0 0
	return 0
	fi
    done

TEXT="\n
ERROR ERROR ! I could not find the install media
in the harddisk hard drive or the CDROM. Please check that:\n
  - You have a CDROM, Windows partition, or Linux partition\n
  - A root directory /veclinux in it\n
  - The bulk files and filelist.txt file in that directory.\n
We will abort for this time."

    $DCMD --backtitle "$BACKTITLE" --title "SOMETHING IS WRONG" \
    --msgbox "$TEXT" 12 66
    clean_exit 1
}

################################################################################
# CHECK MEDIA CHECKSUM
# Media has been mounted on $LOOP_MNT 

gzerror() {
  $DCMD --backtitle "$BACKTITLE" --title "ERROR" --yesno "\n
There's something wrong with the $(basename $1) file.
If you are using a CD-ROM maybe it is dirty, damaged,
or it was burnt with a corrupt ISO file.\n
Do you want to abort the installation ?" 0 0
    if [ $? = 0 ]; then
	clean_exit 1 
    fi
}

menuB()
{
    TITLE="CHECK MEDIA"
    TEXT="\n
The installation media is a $MEDIA_TYPE ($MEDIA_DEV).\n
Do you want to check the installation file for errors ?\n
If there are any errors there's no point installing it.\n
This will take a few minutes, but it is important to\n
check the media unless you're sure it's alright.\n
Check Vector installation files for errors ?:"

    $WCMD --backtitle "$BACKTITLE" --title "$TITLE" --menu "$TEXT" 15 60 2 \
    "CHECK" "Yes please, make sure it is perfect" \
    "SKIP" "Nah ... do not waste my time" \
    2> $freply

    status=$?
    [ $status != 0 ] && return $status

    reply=$(cat $freply)

    dbug "Check=$reply"

    if [ "$reply" = "CHECK" ]; then 
	for fbz2 in $LOOP_MNT/veclinux/*.bz2 ; do
    	    infobox "Checking $fbz2" "Please wait"
    	    bzip2 -t $fbz2 >> $flog 2>&1
	    if [ $? = 0 ]; then
		infobox "File $fbz2 is OK" "Good news"
		sleep 2	    
	    else
		gzerror $fbz2
	    fi
	done
    fi

    return 0

}

##############################################################
# SWAP partitions

build_swap_menu()
{
   MENU=""
   while read LINE; do
      PART=$(echo $LINE | cut -f 1 -d ' ')
      SIZE=$(echo $LINE | cut -f 4 -d ' ')
      MENU="$MENU $PART size=$SIZE on"
   done
   dbug "SWAP MENU=$MENU"
}

menuC()
{

    fdisk -l | grep "Linux swap" > /tmp/hdlist
    build_swap_menu < /tmp/hdlist

    if [ -z "$MENU" ]; then
	TITLE="NO SWAP" infobox "Skipping swap installation ..."
	sleep 3
	return 0
    fi

    TITLE="SWAP PARTITIONS"
    DIMENSION="18 70 4"
    TEXT="\n
Linux uses a swap partition for virtual memory, thus
expand the capacity of the actual RAM. Normally, you should
have one swap partition twice the size of your RAM. 
If you have more than one harddisk, having one swap
partitions on each harddisk can increase performance.\n
Use [SPACE BAR] to enable the swap partition then press OK:"

    $WCMD --backtitle "$BACKTITLE" --title "$TITLE" \
    --checklist "$TEXT" $DIMENSION $MENU 2> $freply

    status=$?
    [ $status != 0 ] && return $status

    SWAP_DEVS=$(cat $freply | sed 's/"//g')
    dbug SWAP=$SWAP_DEVS

    return 0
}


##################################################################################
# set ROOT PARTITIONS

build_root_menu()
{
   while read LINE; do
      PART=$(echo $LINE | cut -f 1 -d ' ')
      SIZE=$(echo $LINE | cut -f 4 -d ' ')
      MENU="$MENU $PART size=$SIZE"
   done
}

menuD() {

    ## Select linux partitions type 83
    ## This will miss linux RAID since I'm not sure how to setup RAID for /root
    ## Somebody please fix this
    fdisk -l | grep -e "83 *Linux" > /tmp/hdlist
    
    MENU=""
    build_root_menu < /tmp/hdlist
    if [ -z "$MENU" ]; then
	errorbox "No linux partition found. Let's go back to square one ..."
	clean_exit
    fi

    TITLE="ROOT PARTITION"
    DIMENSION="20 60 8"
    TEXT="\n
Now we need a partition for root (the most top level directory).
It will contain all system and program files, so make sure it 
has enough size.\n
Please choose the root partition:" 

    $WCMD --backtitle "$BACKTITLE" --title "$TITLE" \
    --menu "$TEXT" $DIMENSION $MENU 2> $freply

    status=$?
    [ $status != 0 ] && return $status

    ROOT_DEV=$(cat $freply)

    dbug "ROOT=$ROOT_DEV"    
    return 0
}


#############################################################################
# FORMAT ROOT
menuE() {

TITLE="ROOT FILESYSTEM"
DIMENSION="20 74 3"
TEXT="\n
You have selected $ROOT_DEV for root installation. It must be formated.
If not sure, you may go back. Otherwise choose the filesytem type
for this partition. The EXT2 filesystem has been the standard on linux 
for many years but has some limitations. The EXT3 system is relativly new
but offers a journaling system that is much more reliable in the case
of an unexpected shutdown due to a system failure. Reiserfs
again is relatively new and some claim it's better than EXT3.\n
Your's to decide:"

    $WCMD --backtitle "$BACKTITLE" --title "$TITLE" \
    --menu "$TEXT" $DIMENSION \
"ext2"  "Older proven linux file sytem" \
"ext3"  "Extend ext2 with journaling file system" \
"reiserfs" "The reiser journaling filesystem" \
2> $freply

    status=$?
    [ $status != 0 ] && return $status

    ROOT_FS=`cat $freply`
    
    dbug "ROOT_FS=$ROOT_FS"
    return 0
}


#############################################################################
# Select home partition"

build_home_menu()
{
   while read LINE; do
      PART=$(echo $LINE | cut -f 1 -d ' ')
      ## Skip root
      if [ "$PART" != "$ROOT_DEV" ]; then
         SIZE=$(echo $LINE | cut -f 4 -d ' ')
         MENU="$MENU $PART size=$SIZE"
	 dbug "home_menu=$PART"
      fi
   done
}

menuF() {
    ## in case of returning, umount this first

    ## Select linux partitions
    fdisk -l | grep -e "83 *Linux" > /tmp/hdlist
    ## fdisk -l | grep -e "fd *Linux" >> /tmp/hdlist

    MENU=""
    build_home_menu < /tmp/hdlist
    if [ -z "$MENU" ]; then
	errorbox "No partition for home." "WARNING"
	HOME_DEV=""
	return 0
    fi

    TITLE="HOME PARTITION"
    TEXT="\n
The /home partition is intended for storing your data. Separating 
this partition from the root allows you to keep the data if you 
reinstall the system and also to share the data if you install 
many distros in this computer.\n
Select the partition you want to use as /home:"
    DIMENSION="20 70 6"

    $WCMD --backtitle "$BACKTITLE" --title "$TITLE" \
    --menu "$TEXT" $DIMENSION $MENU 2> $freply

    status=$?
    [ $status != 0 ] && return $status

    HOME_DEV=$(cat $freply)

    dbug "$HOME=$HOME_DEV"
    
    return 0
}


#############################################################################
# FORMAT HOME
menuG() {

## Skip if no home
[ -z $HOME_DEV = "" ] && return 0

TITLE="HOME FILESYSTEM"
DIMENSION="18 70 4"
TEXT="\n
You have selected $HOME_DEV for /home. If this partition
contains your old data DO NOT format it. However, if this
is a newly created  partition, you MUST format it using 
a file system type. Reiserfs or ext3 is
recomended since they are more reliable.\n
Select KEEP or format with a particular file system:"

    $WCMD --backtitle "$BACKTITLE" --title "$TITLE" \
    --menu "$TEXT" $DIMENSION \
"KEEP" "Do not format this partition, keep the old data" \
"reiserfs" "format with reiser journaling filesystem" \
"ext3"  "format with ext3 journaling file system" \
"ext2"  "format with the classic linux filesytem" \
2> $freply

    status=$?
    [ $status != 0 ] && return $status

    HOME_FS=`cat $freply`
    
    dbug "HOME_FS=$HOME_FS"
    return 0
}


###########################################################################
# Select optional packages
# The veclinux directory should contais the bz2 file 
# txt file for description

build_bulk_menu()
{
   if [ -f $LOOP_MNT/veclinux/filelist.txt ]; then
      grep -e "^[^#]" $LOOP_MNT/veclinux/filelist.txt | while read line; do
	 bulk=$(echo $line | cut -f 1 -d ':')
         desc=$(echo $(echo $line | cut -f 3 -d ':'))
	 size=$(echo $(echo $line | cut -f 2 -d ':'))
	 size=$(expr $size / 1024)
	 if echo $line | grep -q "required"; then
	    state="on"
	 else
	    state="off"
	 fi 
	 echo "'$bulk'" "'$desc [$size MB]' $state \\"
      done
   else
      for bulk in $LOOP_MNT/veclinux/*.bz2; do   
	 echo "'$bulk'" "'bulk of $bulk' \\"
      done
   fi
}


menuH() {

TITLE="BULK INSTALLATION"
DIMENSION="20 74 8"
TEXT="\n
Vector Linux uses bulk installation method, instead of\n
individual packages. Therefore you will get a highly integrated\n
well tested system in a snap. Just select the bulks you want:"

    echo '$WCMD --backtitle "$BACKTITLE" --title "$TITLE" \' > $fmenu
    echo '--checklist "$TEXT" $DIMENSION \' >> $fmenu
    build_bulk_menu >> $fmenu
    echo '2> $freply' >> $fmenu

    cat $fmenu >> $flog
    . $fmenu
    
    status=$?
    [ $status != 0 ] && return $status

    BULK_FILES=$(cat $freply | sed 's/"//g')
    return 0
}

###########################################################################
# Confirmation


menuI() {

TITLE="READY TO INSTALL"
DIMENSION="18 70 2"
TEXT="\n
We are going to install Vector Linux on your system with
these settings:\n
    SWAP  : $SWAP_DEVS \n
    ROOT  : $ROOT_DEV ($ROOT_FS)\n
    HOME  : $HOME_DEV ($HOME_FS)\n
    BULKS : $BULK_FILES \n\n
There is no way back. Say 'come on' when you are ready ... :"

    $WCMD --backtitle "$BACKTITLE" --title "$TITLE" \
    --menu "$TEXT" $DIMENSION \
    "INSTALL" "Come on mate, go for it !!!" \
    "ABORT" "I'm scared my system will turn into toast" \
    2> $freply

    status=$?
    [ $status != 0 ] && return $status

    case `cat $freply` in
       ABORT)
	    echo -e $BLINK ${YELLOW}Chicken ${LTRED}!${LTGREEN}!${LTBLUE}! $OFF
	    sleep 5
	    clean_exit 1
        ;;
    esac
    return 0
}


####################################################
# Install the system !!!!

# format <device> <file_system>
format_dev()
{
    dbug "Format $1 with $2"
    case $2 in
    "ext2")
	infobox "Formating $1 with $2"
	mke2fs -q $1 >> $flog 2>&1
	;;
    "ext3")
	infobox "Formating $1 with $2"
	mke2fs -q -j $1 >> $flog 2>&1
	;;
    "reiserfs")
	infobox "Formating $1 with $2"
	mkreiserfs -ff $1 >> $flog 2>&1
	sleep 2
	;;
    *)
	infobox "Skipping $1. Not formated !"
	sleep 2
	;;
    esac
    if [ ! $? = 0 ]; then
	$DCMD --backtitle "$BACKTITLE" --title "ERROR" --msgbox "\n
Cannot format $1 with $2 filesystem.\n
Sorry but the installation should be aborted" 7 40
	clean_exit 1 
    fi
}

# mount <device> <mount_point> <file_system>
mount_dev()
{
    infobox "Mounting $1 ..."
    dbug "mount $1 $2 -t $3"
    mkdir -p $2 >> $flog 2>&1
    umount $2 >> $flog 2>&1
    if [ "$3" = "KEEP" ]; then
	dbug "mount $1 $2 -t auto"
     	mount $1 $2 -t auto >> $flog 2>&1
    else
	dbug "mount $1 $2 -t $3"
     	mount $1 $2 -t $3 >> $flog 2>&1
    fi
    if [ $? != 0 ]; then
	$DCMD --backtitle "$BACKTITLE" --title "ERROR" --msgbox "\n
Cannot mount $1 with $3 filesystem.\n
Sorry but the installation must be aborted" 7 40
	clean_exit 1 
    fi
    sleep 2
}

fstab_option()
{
    case $1 in
    "ext2")
	echo "defaults"
	;;
    "ext3")
	echo "defaults"
	;;
    "reiserfs")
	echo "notail"
	;;
    "vfat")
	echo "umask=0,shortname=mixed,quiet"
	;;
    *)
        echo "defaults"
	;;
    esac
}

mk_fstab()
{

ROOT_TAB="$ROOT_DEV  /     $ROOT_FS   $(fstab_option $ROOT_FS)  0  1"
if [ "$HOME_DEV" ]; then
    if [ "$HOME_FS" = "KEEP" ]; then
	HOME_TAB="$HOME_DEV  /home   auto   $(fstab_option $HOME_FS) 0 2"
    else
	HOME_TAB="$HOME_DEV  /home   $HOME_FS   $(fstab_option $HOME_FS) 0 2"
    fi
else
    HOME_TAB=""
fi

cat <<EOF
# /etc/fstab: static file system information.
#
# The following is an example. Please see fstab(5) for further details.
# Please refer to mount(1) for a complete description of mount options.
#
# Format:
# <file system>   <mount point>   <type>   <options>   <dump>	<pass>
#
# dump(8) uses the <dump> field to determine which file systems need
# to be dumped. fsck(8) uses the <pass> column to determine which file
# systems need to be checked--the root file system should have a 1 in
# this field, other file systems a 2, and any file systems that should
# not be checked (such as MS-initrd/mnt or NFS file systems) a 0.

# This is a root linux $type partition:
$ROOT_TAB
$HOME_TAB

# This is a linux ext2 partition:
#/dev/hda2	/mnt/linux	ext2	defaults	0 2

# The 'noauto' option indicates that the file system should not be mounted
# with 'mount -a' 'user' indicates that normal users are allowed to mount
# the file system.
/dev/cdrom	/mnt/cdrom	iso9660	defaults,noauto,ro,user	0 0
/dev/fd0	/mnt/floppy	auto	defaults,noauto,user	0 0
#/dev/fd1	/mnt/floppy	auto	defaults,noauto,user	0 0

# If you have a ls-120 floppy drive, it could be on /dev/hda b c d etc.
#/dev/hdd	/mnt/ls120	auto	defaults,noauto,user	0 0

# NFS file systems:
#linux01.gwdg.de:/suse/6.3/i386.de  /mnt/nfs  nfs  defaults  0 0

# proc file system:
proc	/proc	proc	defaults	0 0

# Unix98 devpts filesystem:
none  /dev/pts  devpts  gid=5,mode=666  0 0

# Shared memory filesystem:
#none   /var/shm    shm   defaults  0  0
# Basic USB filesystem
usbdevfs  /proc/bus/usb  usbdevfs  defaults,noauto  0 0

# For dos partition use type 'msdos'.
# For win95/98 fat16 or FAT32 partition use type 'vfat'.
#/dev/hda1   /mnt/win   vfat   umask=0,quiet,shortname=mixed  0  0

# The 'sw' option indicates that the swap partition is to be activated
# with 'swapon -a'.
EOF

# swap
for DEV in $SWAP_DEVS; do
  echo "$DEV   none   swap   sw   0   0"
done

}

menuJ()
{

#clear

#echo FAKE INSTALL
#echo 1. Format $ROOT_DEV with $ROOT_FS
#echo 2. Format $HOME_DEV with $HOME_FS
#echo 3. Mount $ROOT_DEV to $ROOT_MNT
#echo 4. Mount $HOME_DEV to $HOME_MNT
#echo 5. Extract $BULK_FILES to $ROOT_MNT
#for i in 1 2 3 4 5 6 7 8 9; do
#   echo -n .
#done

#echo Finished.
#echo The istallation will continue from chrooted environment.
#echo "END OF THE DEMO"
#echo "Press enter to continue"
#read
#clean_exit

# Making and activating swap devices
for DEV in $SWAP_DEVS; do 
    infobox "Initialising swap partition $DEV ..."
#    if ! swapon -s | grep -qe "^$DEV"; then
	mkswap $DEV >> $flog 2>&1
	sleep 1
	swapon $DEV >> $flog 2>&1
#    fi
    sleep 1
done

format_dev $ROOT_DEV $ROOT_FS
mount_dev $ROOT_DEV $ROOT_MNT $ROOT_FS

if [ "$HOME_DEV" ]; then
    format_dev $HOME_DEV $HOME_FS
    mount_dev $HOME_DEV $HOME_MNT $HOME_FS
fi

for BULK in $BULK_FILES; do
    SIZE=`grep $BULK $LOOP_MNT/veclinux/filelist.txt | cut -f 2 -d ':'`
    echo "3" > /tmp/delay
    tar -xjpf $LOOP_MNT/veclinux/$BULK -C $ROOT_MNT &
    $vdir/dfgauge $ROOT_DEV $SIZE "$BULK"
done

mkdir -p $ROOT_MNT/etc/rc.d
mk_fstab > $ROOT_MNT/etc/fstab

# copy  keymap
if [ -x /tmp/rc.keymap ]; then
   cp /tmp/rc.keymap $ROOT_MNT/etc/rc.d
fi

chroot $ROOT_MNT /sbin/setup-config $ROOT_DEV

$DCMD --backtitle "So let the games begin !!" \
--title "WELCOME TO VECTOR-LINUX" --msgbox \
"Congratulation. Your Vector Linux is ready.\n 
Let's reboot and start enjoying it ...!!!." 8 60 

clear
echo -e "$YELLOW Rebooting ................ $OFF"

for MNT in $HOME_MNT $ROOT_MNT $LOOP_MNT; do
   umount $MNT
   sleep 3
done

swapoff -a

sync 2>/dev/null

reboot

clean_exit 1

}

wizard menuA menuB menuC menuD menuE menuF menuG menuH menuI menuJ
return $?


