#!/bin/sh
# Vector Linux First Time Configuration
#
# This script is a bit complicated, because there are many scenarios
# during the SETUP (stage1) and the FIRST BOOT (stage2)
#
# 1. STAGE 1
# For stage1, this script is called by setup-install (in the initrd)
# There are two possible cases: NORMAL and SHORT 
#
# 1.a. NORMAL STAGE 1
# This happen during normal setup from CDROM, or Windows loadlin
# The setup-install calls this script like this: 
#   chroot /mnt/target /sbin/config-stage1 vector-virgin <root-device> [$KEYMAP]
#
# Then, there are 3 possible scenarios:
#
# 1.a.1 NORMAL STAGE 1 - CORRECT KERNEL
# If the running kernel is present on the installed system,
# do FULL config then prepare the LIGHT stage2
#
# 1.a.2 NORMAL STAGE 1 - SKIP
# The kernel is correct, but user choose SKIP
# do SHORT config then prepare the HEAVY stage2
#
# 1.a.3. NORMAL STAGE 1 - INCORRECT KERNEL 
# The kernel is not present on the installed system.
# do SHORT config then prepare the HEAVY stage2
# Note: this feature allows the floppy install using small 2.4 kernel 
# although the installed system has the big 2.6 kernel
#
# 1.b. SHORT STAGE 1
# This is the case during direct ISO install by vinstall
# The setup-install calls this script like this: 
#    chroot /mnt/target /sbin/config-stage1 vector-virgin-short <root-device> 
#
# Because the running Linux environment is a stranger, safe option is
# do the SHORT config then prepare the HEAVY stage2
#
#
# 2. STAGE 2
# Stage 2 is prepared by STAGE-1 by making an auto-init script 
# /var/log/setup/init/config-stage2
# That auto-init script will be called by rc.S during the boot.
# According on how it is prepared by STAGE-1, the config-stage2 may
# call this script as LIGHT or HEAVY 
#
# 2.a. STAGE 2 HEAVY
# Called like this by config-stage2
#    config-stage1 vector-virgin-heavy <root-device> [$KEYMAP]
# This will do the FULL config
#
# 2.b. STAGE 2 LIGHT
# Called like this by config-stage2
#    config-stage1 vector-virgin-light <root-device> [$KEYMAP]
# This only setup the basic service and congratulates user
#
# Hah ... I can't believe I made this script.
#
# (c) Eko M. Budi, 2004
# (c) Vector Linux, 2004
#
# Released under GNU GPL

export PATH="/sbin:/usr/sbin:/bin:/usr/bin:/usr/X11R6/bin:/opt/bin"

#####################################################
# Init some variables
RUN_MODE=$1
ROOT_DEVICE=$2 
KEYMAP=$3
KERNEL_VERSION=`uname -r`
SETUP_DIR="/var/log/setup"
INIT_DIR="$SETUP_DIR/init"
TMP_DIR="$SETUP_DIR/tmp"

ACTION_LIST=""

# Ok, now get the functions
vdir=$(dirname $0)
. $vdir/vasm-functions

check_root

#####################################################
# check stage
if [ -x $INIT_DIR/config-stage2 ]; then
    CONFIG_STAGE=2
    rm -f $INIT_DIR/config-stage2
fi
if [ -x $INIT_DIR/zz.gnucash ]; then
    CONFIG_STAGE=1
fi

## Making config-stage2
set_stage2_light()
{
mkdir -p $INIT_DIR
chmod 700 $INIT_DIR
cat <<EOF > $INIT_DIR/config-stage2
#!/bin/sh

exec /sbin/config-stage1 vector-virgin-light $ROOT_DEVICE $KEYMAP

EOF
chmod a+x $INIT_DIR/config-stage2
}

set_stage2_heavy()
{
mkdir -p $INIT_DIR
chmod 700 $INIT_DIR
cat <<EOF > $INIT_DIR/config-stage2
#!/bin/sh

exec /sbin/config-stage1 vector-virgin-heavy $ROOT_DEVICE $KEYMAP

EOF
chmod a+x $INIT_DIR/config-stage2
}

# Set default boot mode 
set_bootmode()
{
   finit=/etc/inittab
   cat $finit \
   | sed "s/^id:[0-9]:initdefault:/id:$1:initdefault:/" > ${finit}.new \
   && mv -f ${finit}.new $finit
}

# Set default boot mode 
get_bootmode()
{
   BOOT_MODE=2
   finit=/etc/inittab
   LINE=`grep "^id:[0-9]:initdefault:"`
   if [ $LINE ]; then
      BOOT_MODE=`echo $LINE | cut -f2 -d:`
   fi
}

# Initializing & set keymap
mk_keymap() {
MAPNAME=$1
cat <<EOF
#!/bin/sh
#
# /etc/rc.d/rc.keymap
#
# This file is called from: /etc/rc.d/rc.M
#
# Linux `date '+%a %b %e %Y'`

# You can load another keyboard keymap e.g. 'loadkeys fr' = french etc.
# The keymaps are in the /usr/lib/kbd/keymaps/i386 directory.

if [ -x /usr/bin/loadkeys ]; then
loadkeys $MAPNAME

# This is so you can open other consoles using the left-[Alt] & [Up]-arrow key.
echo "alt keycode 103 = Spawn_Console" | /usr/bin/loadkeys
fi

EOF
}

set_keymap() {
## Detect if we need a KEYMAP menu
KMAPSET="off"
if [ "$KEYMAP" ]; then
    # If the keymap is there, just create it
    if [ -r /usr/share/kbd/keymaps/i386/qwerty/$KEYMAP.map.gz ] || \
	[ -r /usr/share/kbd/keymaps/i386/qwertz/$KEYMAP.map.gz ] || \
    	[ -r /usr/share/kbd/keymaps/i386/azerty/$KEYMAP.map.gz ]; then
	infobox "Setting up keymap $KEYMAP"
	mk_keymap $KEYMAP > /etc/rc.d/rc.keymap
	chmod +x /etc/rc.d/rc.keymap
	sleep 2
    else
	KMAPSET="on"
        KEYMAP="us"
    fi
else
    KEYMAP="us"
fi
}


# detect RAID harddisk, 
# then change the default vmlinuz to vmlinuz-raid or vmlinuz-sata
set_vmlinuz() {
    if grep -qe "^md.*:" /proc/mdstat 2>/dev/null; then
	VMOLD=`readlink /boot/vmlinuz`
	VMVERSION=${VMOLD##*-}
	if [ -f /boot/vmlinuz-raid-$VMVERSION ]; then
	    (cd /boot; rm -rf vmlinuz; ln -sf vmlinuz-raid-$VMVERSION vmlinuz)
	elif [ -f /boot/vmlinuz-sata-$VMVERSION ]; then
	    (cd /boot; rm -rf vmlinuz; ln -sf vmlinuz-sata-$VMVERSION vmlinuz)
	fi
    fi
}


##################################################################
# INDIVIDUAL DIALOGS

#---------------------------------------------
menu_keymap()
{
    echo $ACTION_LIST | grep -qw "KEYMAP" || return $1
    if [ -d /etc/X11/xkb ]; then
	$vdir/vxkbset
    else
	$vdir/vkmapset
    fi
}

#----------------------------------------------------------------
# Set the zone first, so every time stamp will be right after this
menu_zone()
{
    echo $ACTION_LIST | grep -qw "ZONE" || return $1
    $vdir/vzoneset
}

#---------------------------------------------
menu_restore()
{
    echo $ACTION_LIST | grep -qw "RESTORE" || return $1
    $vdir/vbackupsys --install
}

#---------------------------------------------
menu_autosetup()
{
    echo $ACTION_LIST | grep -qw "AUTOSETUP" || return $1
    if [ $1 = 0 ]; then
	$vdir/vhwconf
	## Update kernel modules
	depmod -A > /dev/null 2>&1
    else
	return $1
    fi
    return 0
}

#---------------------------------------------
menu_net()
{
    ifconfig -s|grep -v Iface|grep -v lo|cut -d " " -f 1 >>/etc/sysconfig/nics
    nics=`cat /etc/sysconfig/nics|wc -l`
    if [ $nics -gt 1 ]; then
      INTERFACES=$( perl -we 'print join(q( ), map { chomp $_; $_ } <>), "\n";' /etc/sysconfig/nics)
      sed "s/eth0/$INTERFACES/g" /etc/ifplugd/ifplugd.conf.new
      mv /etc/ifplugd/ifplugd.conf /etc/ifplugd/ifplugd.conf.bak
      mv /etc/ifplugd/ifplugd.conf.new /etc/ifplugd/ifplugd.conf
    fi
    echo $ACTION_LIST | grep -qw "NETWORK" || return $1
    if grep eth0 /etc/modprobe.d/network.conf &>/dev/null || \
       grep eth0 /etc/modprobe.conf &>/dev/null || \
       grep eth0 /etc/modules.conf &>/dev/null || \
       grep NETCARD0 /etc/sysconfig/vector &>/dev/null ; then
	# Setup loopback
	# ifconfig lo 127.0.0.1 netmask 255.255.255.0 up
	# setup networking
	$vdir/vnetconf --no-start
	return $?
    else
	if [ $1 = 0 ]; then
	    infobox "Network card is not present. Skipping"
	    sleep 2
	fi
	return $1
    fi
    return 0
}

#---------------------------------------------
menu_x()
{

    echo $ACTION_LIST | grep -qw "XWINDOW" || return $1
XORG=`which Xorg`
    if [ -x /usr/X11R6/bin/XFree86 ]; then
	$vdir/vmkfx86cfg || return $?
    elif [ -x $XORG ]; then
	$vdir/vxconf || return $?
    else
	if [ $1 = 0 ]; then
	    infobox "X-Windows is not present. Skipping"
	    sleep 2
	fi
	return $1
    fi
    set_bootmode 4
    $vdir/vbootset
    if [ "$RUN_MODE" = "vector-virgin-heavy" ]; then
	telinit Q
    fi
    return 0
}

#---------------------------------------------
menu_alsa()
{
    echo $ACTION_LIST | grep -qw "SOUND" || return $1
    chmod +x /etc/rc.d/rc.alsa
    #$vdir/valsaconf
    /usr/sbin/alsaconf
}

#---------------------------------------------
menu_hw()
{
    echo $ACTION_LIST | grep -qw "HWINIT" || return $1
    $vdir/vhwset
}

#---------------------------------------------
menu_srv()
{
    echo $ACTION_LIST | grep -qw "SRVINIT" || return $1
    $vdir/vsrvset --default
}

#---------------------------------------------
menu_admin() {

echo $ACTION_LIST | grep -qw "ADMIN" || return $1

DEF_ITEM="ROOT"
while [ 0 ]; do
TITLE="USER ADMINISTRATION"
TEXT="\n
Linux is a secure system, thus every user must have an account
for logging into the system. The first and the most powerful
account is called a 'root'. You should login as root on special
occasions only such as administering the system. For normal
every day work, it is safer to login as an ordinary user.\n\n
The following menu allows you to change the root password and 
to create some ordinary users."

$WCMD --backtitle "$BACKTITLE" --title "$TITLE" \
--default-item $DEF_ITEM --menu "$TEXT" 18 68 3 \
"ROOT"  "change root password" \
"USER"  "add a new user" \
"DONE"  "finish administering the users" \
2>$freply || return $?

case `cat $freply` in
    ROOT)
    $vdir/vpasswd root
    DEF_ITEM="USER"
    ;;
    USER)
    $vdir/vuseradd
    DEF_ITEM="DONE"
    ;;
    DONE)
    return 0
    ;;
esac

done
}

#---------------------------------------------
menu_finish1_nokernel()
{
TEXT="\n
Vector Linux has been installed successfully.\n
However, we have to reboot for proper configuration."

$DCMD --backtitle "$BACKTITLE" --title "REBOOT FOR PROPER KERNEL" \
--msgbox "$TEXT" 9 58 2> /dev/null

clean_exit 0
}


#---------------------------------------------
menu_finish1_short()
{

TEXT="\n
Vector Linux has been installed successfully.\n
Let's reboot and continue with the configuration."

$DCMD --backtitle "$BACKTITLE" --title "REBOOT IS NEEDED" \
--msgbox "$TEXT" 9 54 2> /dev/null

clean_exit 0
}


#---------------------------------------------
menu_finish1()
{
    infobox "Vector Linux has been installed and configured" "SUCCESS"
    set_stage2_light
    sleep 3
    clean_exit 0
}

#---------------------------------------------
menu_finish2_light()
{

TEXT="\n
Vector Linux is now ready for you.\n
Enjoy and happy Vectoring ..."

$DCMD --backtitle "$BACKTITLE" --title "CONGRATULATIONS" \
--msgbox "$TEXT" 8 40 2> /dev/null

clear
echoc "Vector Linux will be ready on the road in a moment ..." green 
echo "Backing up system files .."

# copy a new skeleton for root
#cd /root; cp -a /etc/skel/. .) &> /dev/null
touch /etc/fstab &> /dev/null
touch /etc/lilo.conf &> /dev/null

# Backup 
backupsys &> /dev/null
echo "Updating database .."
updatedb & &> /dev/null

sleep 5

clean_exit 0
}

#---------------------------------------------
menu_finish2_heavy()
{

TEXT="\n
Vector Linux is ready at your service.\n
You may use VASM for further configuration.\n
Enjoy and happy Vectoring !!!"

$DCMD --backtitle "$BACKTITLE" --title "CONGRATULATIONS" \
--msgbox "$TEXT" 11 48 2> /dev/null

clear
echoc "Final finishing touch ..." green

# copy a new skeleton for root
#(cd /root; cp -a /etc/skel/. .) &> /dev/null

echo "Backing up system files .."
touch /etc/fstab &> /dev/null
touch /etc/lilo.conf  &> /dev/null
backupsys &> /dev/null

#echo "Updating database for the first time ..."
#updatedb &> /dev/null

sleep 2

# Reboot for first time install
if [ "$CONFIG_STAGE" = "2" ]; then
    clear
    echo "For stability, we have to reboot. Please be patient ... "
    reboot
    #telinit 6
    clean_exit 0
fi
}

menu_finish_auto()
{
TEXT="\n
Vector Linux has been reconfigured.\n
Keep happy vectoring ..."
TITLE="DONE"

$DCMD --backtitle "$BACKTITLE" --title "$TITLE" \
--msgbox "$TEXT" 8 40 2> /dev/null
clean_exit 0
}

###################################################################
# Wizard utilities

confirm_exit()
{
TEXT="\n
Configuration has not finished yet.\n
Are you sure to quit now ?"
    $DCMD --title "CANCEL CONFIGURATION" --yesno "$TEXT" 7 40 2> /dev/null
    if [ $? = 0 ]; then
        clean_exit 1
    fi
}

wizard1()
{
   if [ -z "$1" ]; then
      # reaching here mean the wizard was a success
      clean_exit 0;
   fi

   local STATUS=0
   local PROG=$1
   shift
   
   # Invoke the menu
   while [ 0 ]; do
     dbug $PROG
     $PROG $STATUS
     STATUS=$?
     dbug $PROG result=$STATUS
     case $STATUS in
       0)   # OK
       wizard1 "$@"
       STATUS=$?
       ;;
       2|3|255)   # BACK
       return 3
       ;;     
       1) # Cancel 
       confirm_exit
       ;;
     esac
   done
}

#############################################################
# Here we go the main configuration
menu_config()
{

FINISH=$1

TITLE="VECTOR LINUX CONFIGURATION"
TEXT="\n
So far so good. Now we are going configure this puppy.\n
The steps are quick and easy, because we will use auto-detect.\n
However, you may skip some steps if you like.\n
Please use [space] bar to toggle the steps then hit <OK>:"

if ls /home/backupsys/*.tar.bz2 &>/dev/null; then

DIMENSION="20 74 9"

$DCMD --backtitle "$BACKTITLE" --title "$TITLE" \
--checklist "$TEXT" $DIMENSION \
"KEYMAP" "set keyboard map (default="$KEYMAP")" $KMAPSET \
"ZONE" "set time zone (essential)" on \
"RESTORE" "restore backupsys found on /home (optional)" off \
"AUTOSETUP" "detect and set basic hardware (essential)" on \
"NETWORK" "set networking (recommended)" on \
"SOUND" "set sound system (recommended)" on \
"XWINDOW" "set X-Window GUI system (recommended)" on \
"HWINIT" "trimmed down hardware initialization (optional)" on \
"ADMIN" "set root password and add users (recommended)" on \
2>$freply || return $?

ACTION_LIST=`cat $freply`

wizard1 menu_keymap menu_zone menu_restore menu_autosetup menu_net \
   menu_alsa menu_x menu_hw menu_srv menu_admin $FINISH

else
DIMENSION="19 74 8"
$DCMD --backtitle "$BACKTITLE" --title "$TITLE" \
--checklist "$TEXT" $DIMENSION \
"KEYMAP" "set keyboard map (default="$KEYMAP")" $KMAPSET \
"ZONE" "set time zone (essential)" on \
"AUTOSETUP" "set basic hardware (essential)" on \
"NETWORK" "set networking (optional)" on \
"SOUND" "set sound system (optional)" on \
"XWINDOW" "set X-Window GUI system (optional)" on \
"HWINIT" "trimmed down hardware initialization (optional)" on \
"ADMIN" "set root password and add users (recommended)" on \
2>$freply || return $?

ACTION_LIST=`cat $freply`

wizard1 menu_keymap menu_zone menu_autosetup menu_net \
   menu_alsa menu_x menu_hw menu_srv menu_admin $FINISH
fi

}

#############################################################
# Here we go the main procedures for STAGE 1

stage1_init()
{
# Do something to impress
infobox "Checking and initializing ..." "Wait a moment please"

# check if we are running in a correct chroot directory
CHECK_FILES="/boot/vmlinuz /etc/vector-version"

for cfile in $TEST_FILES; do
  if [ ! -f $cfile ]; then
     errorbox "Cannot find $cfile. This is not me. Bailing out ...!"
     clean_exit 1  
  fi
done

# Setup stage2-heavy as the default
set_stage2_heavy

# Load libraries
ldconfig &> /dev/null
depmod -A &> /dev/null

# make standard directories
mkdir -p /mnt/cdrom /mnt/win /mnt/linux /mnt/pendrive /mnt/floppy /mnt/loop

# initial settings
set_vmlinuz
set_keymap
set_bootmode 2

# Setting up services
#service -b &> /dev/null

# Cleanup KDE menu
kmenucleanup &> /dev/null

}

menu_lilo()
{
    while [ 0 ]; do 
	$vdir/vliloconf / $ROOT_DEVICE && return 0
	confirm_exit
    done
}

##-----------------------------------
stage1_short()
{
    stage1_init
    menu_lilo
    #$vdir/vhalswitch
    menu_finish1_short
    sleep 2
}

##------------------------------------
stage1()
{
    # go long only if we have the correct kernel modules
    if [ -d /lib/modules/$KERNEL_VERSION ] ||
       [ -d /lib/modules/${KERNEL_VERSION}n ] ; then
	stage1_init
	menu_lilo
    #$vdir/vhalswitch
#	check_xwindow
	while [ 0 ]; do
	    menu_config menu_finish1
	    confirm_exit
	done
    else
	stage1_init
	menu_lilo
    #$vdir/vhalswitch
	menu_finish1_nokernel
	sleep 2
    fi
    return $?
}

#############################################################
# STAGE 2
stage2_init()
{
# Do something to impress
infobox "Continuing first time configuration ..." "Almost there"

# check if we are running in a correct system
CHECK_FILES="/boot/vmlinuz /etc/vector-version"
for cfile in $TEST_FILES; do
  if [ ! -f $cfile ]; then
     errorbox "Cannot find $cfile. This is not me. Bailing out ...!"
     clean_exit 1  
  fi
done

sleep 2
}

##------------------------------------
stage2_light()
{
   stage2_init
   menu_finish2_light
}

##------------------------------------
stage2_heavy()
{
  stage2_init
  ldconfig &> /dev/null
  depmod -A &> /dev/null
  set_keymap
 # check_xwindow
  while [ 0 ]; do
    menu_config menu_finish2_heavy
    confirm_exit
  done
}

########################################################
auto_setup()
{

#check_xwindow

TITLE="VECTOR LINUX AUTOSETUP"
TEXT="\n
The autosetup walks you through a series of essential 
configurations as listed below.\n
Please use [space] bar to toggle the steps then hit <OK>:"

DIMENSION="18 74 6"
$DCMD --backtitle "$BACKTITLE" --title "$TITLE" \
--checklist "$TEXT" $DIMENSION \
"AUTOSETUP" "set basic hardware (essential)" on \
"NETWORK" "set networking (optional)" on \
"SOUND" "set sound system (optional)" on \
"XWINDOW" "set X-Window GUI system (optional)" on \
"HWINIT" "enable hardware initialization (optional)" on \
"SRVINIT" "enable services initialization (optional)" on \
2>$freply || return $?

ACTION_LIST=`cat $freply`

#echo $ACTION_LIST
wizard1 menu_autosetup menu_net \
   menu_alsa menu_x menu_hw menu_srv menu_finish_auto
}

###################################################################
# Here we go the main menu

case $RUN_MODE in
    vector-virgin)
	infobox "Let's Configure the system."
#        sh /var/log/scripts/gsb-desktop* & 2>/dev/null
#	sleep 10
#	rm /usr/share/applications/wbar.desktop &>/dev/null
#	rm -r /root/.mc &>/dev/null
	for i in /usr/share/icons/*;do cd $i 2>/dev/null && if [ -e convert.sh ];then sh convert.sh & 2>/dev/null;fi;done
	chmod +x /etc/rc.d/rc.udev
         for i in /var/log/scripts/x11-fonts*;do sh $i &>/dev/null;done
	update-mime-database /usr/share/mime/
	cd /usr/lib && ln -sf preloadable_libintl.so libgnuintl.so.8 && rm libintl.so 2>/dev/null; ln -s preloadable_libintl.so libintl.so
        stage1
	;;
    vector-virgin-short)
	infobox "Let's Configure the system."
#        sh /var/log/scripts/gsb-desktop* & 2>/dev/null
#	sleep 10
	for i in /usr/share/icons/*;do cd $i 2>/dev/null && if [ -e convert.sh ];then sh convert.sh & 2>/dev/null;fi;done
	chmod +x /etc/rc.d/rc.udev
        for i in /var/log/scripts/x11-fonts*;do sh $i &>/dev/null;done
        update-mime-database /usr/share/mime/
	cd /usr/lib && ln -sf preloadable_libintl.so libgnuintl.so.8 && rm libintl.so 2>/dev/null; ln -s preloadable_libintl.so libintl.so
        stage1_short
	;;
    vector-virgin-heavy)
	for i in /usr/share/icons/*;do cd $i 2>/dev/null && if [ -e convert.sh ];then sh convert.sh & 2>/dev/null;fi;done
	stage2_heavy
	;;    
    vector-virgin-light)
	for i in /usr/share/icons/*;do cd $i 2>/dev/null && if [ -e convert.sh ];then sh convert.sh & 2>/dev/null;fi;done
	stage2_light
	;;
    gui-installer)
    cat "verbose" >/proc/splash
    infobox "Let's finish system Configuration."
    #    sh /var/log/scripts/gsb-desktop* & 2>/dev/null
    #     for i in /var/log/scripts/x11-fonts*;do sh $i &>/dev/null;done
#	sleep 3
        #$vdir/vhalswitch
        ACTION_LIST="AUTOSETUP NETWORK SOUND XWINDOW HWINIT SRVINIT"
        wizard1 menu_finish2_heavy
	;;
    *)
	for i in /usr/share/icons/*;do cd $i 2>/dev/null && if [ -e convert.sh ];then sh convert.sh & 2>/dev/null;fi;done
	# normal autosetup
	auto_setup
	;;
esac

clean_exit 0
