#!/bin/bash
###################################################################
#  REMASTERSYS                                                    #
#    Under the GNU GPL2 License                                   #
#    Copyright (C) 2021-2023 Daniel "Nerun" Rodrigues             #
#    Copyright (C) 2007-2013 Tony "Fragadelic" Brijeski           #
#    Full copyright notice: /usr/share/doc/remastersys/copyright  #
###################################################################

# SYSTEM LOCALIZATION
# Target to file:
# /usr/share/locale/(language code)/LC_MESSAGES/remastersys-installer.mo
TEXTDOMAIN=remastersys-installer

Superuser=$"ERROR: This script must run as superuser. Try with \"sudo\"."

# LIBRARIES
. /usr/lib/remastersys/libremastersys.sh

IsRoot # libremastersys.sh

if [[ "$1" == @("-h"|"-?"|"--help") ]]; then
    GiveUserHelp # libremastersys.sh
fi

# set options depending on mode - text or gui
DIALOG="`find_bin dialog`"
HEIGHT="17"
WIDTH="50"
MENUHEIGHT="12"
TITLE="--title "
TEXT=""
ENTRY="--inputbox "
MENU="--menu"
YESNO="--yesno "
MSGBOX="--msgbox "
PASSWORD="--passwordbox "
PARTITIONPROG="cfdisk"
TITLETEXT=$"Remastersys Installer"

# Frequent texts grouped to facilitate internationalization
YES=$"Yes"
NO=$"No"
PICK=$"Pick"
INFO=$"Info"

if [[ "$1" == @("-g"|"--gui") ]]; then
    GUI="$DISPLAY"
fi

if [ "$GUI" != "" ]; then
    notfound=$"not found. Will be installed now."

    testyad=`find_bin yad`
    if [ "$testyad" = "" ]; then
        echo "Yad "$notfound
        apt -y -q install yad
        testyad=`find_bin yad`
    fi

    testgparted=`find_bin gparted`
    if [ "$testgparted" = "" ]; then
        echo "Gparted "$notfound
        apt -y -q install gparted
        testgparted=`find_bin gparted`
    fi

    if [ "$testyad" != "" ]; then
        DIALOGMENU="$testyad --window-icon=/usr/share/icons/hicolor/16x16/apps/remastersys-installer.png --width=600 --height=400 --center"
        DIALOG="$testyad --window-icon=/usr/share/icons/hicolor/16x16/apps/remastersys-installer.png --center --fixed"
        TITLE="--always-print-result --dialog-sep --image=/usr/share/icons/hicolor/48x48/apps/remastersys-installer.png --title="
        TEXT="--text="
        ENTRY="--entry "
        ENTRYTEXT="--entry-text "
        MENU="--list --column=$PICK --column=$INFO"
        YESNO=" --button=$YES:0 --button=$NO:1 "
        MSGBOX=" --button=Ok:0 "
        PASSWORD="--entry --hide-text "

        if [ "$testgparted" = "" ]; then
            PARTITIONPROG="xterm -e cfdisk"
        else
            PARTITIONPROG="gparted"
        fi
    fi
fi

if [ "$DIALOG" = "" ]; then
    echo $"Could not find \"dialog\" or \"yad\". Exiting."
    exit 1
fi

progressbar() {
    tail -f /usr/bin/remastersys-installer | $DIALOG $TITLE"$TITLETEXT" $TEXT"$@" --no-buttons --progress --pulsate --auto-close
}

. /etc/live/config.conf
. /etc/remastersys.conf

if [ "$LIVECDLABEL" != "" ]; then
    TITLETEXT=$"$LIVECDLABEL Installer"
fi

# DIALOGS ######################################################################
# Frequent texts grouped to facilitate internationalization
EXIT=$"Exit"
ExitInstaller=$"Exit Installer"
ExitingInstaller=$"Exiting installer now."
SelectDriveToPartition=$"Select a drive to partition.\nIf the only option you see is \"$ExitInstaller\" then no drive was found."
SelectSwapPartition=$"Select a swap partition to use.\nIf the only option you see is \"$ExitInstaller\" then no swap partition was found."
SelectInstallationPartition=$"Select a partition to install the system on.\nIf the only option you see is \"$ExitInstaller\" then no partition was found."
SelectRootFileSystem=$"Select the file system type of the root partition."
PasswordsDontMatch=$"Passwords do not match. Try again."
IdiomKeyboardLayout=$"The current system language as well as\nthe current keyboard layout will continue to\nbe used by the installer until the end.\nHowever, you can change the language and\nkeyboard layout that will be installed.\n\nDo you want to change?"
ThisIsTheInstaller=$"This is the Live CD installer.\n\nDo you want to continue?"
SelectHomePartition=$"Select a partition to install the /home folder on.\nIf the only option you see is the root partition, then no other partitions were found."
PutHomeInRootPartition=$"put /home on the root partition"
SelectHomeFileSystem=$"Select the home partition file system type"
DontFormatHomePartition=$"Don't format the home partition - not recommended unless you know what you're doing"
CreatePartitions=$"We need to prepare the swap and install the partition now.\n\n$PARTITIONPROG will allow you to create the new partitions.\n\nYou must create or already have at least 1 system partition and 1 swap partition.\n\nIf you already have the partitions set up, just exit $PARTITIONPROG and the installation will continue.\n\nClick OK to continue."
PleaseConfirm=$"Please confirm if this information is correct:\n\n"
Proceed=$"\n\nDo you want to proceed?"
RootPartition=$"Root partition - safe choice if you use a different boot loader"
RootMBRPartition=$"Root partition MBR - this is what you want for a pendrive/USB installation"
SystemClockSetup=$"Is your system clock set to local time?\n\nResponding \"no\" will indicate that it is set to UTC."
SelectWhereInstallGrub=$"Select where to install grub.\n"
DiskMBR=$"Master Boot Record (MBR) of the disk"
SelectTimeZone=$"Select a time zone for your system"

HomeText(){
    # Return global variable HOMETEXT
    HOMEPART="$1"
    HFSTYPE="$2"
    
    if [ "$HOMEPART" != "root" ]; then
        HOMETEXT=$"$HOMEPART will be formatted in $HFSTYPE for use as /home"
    fi

    if [ "$HFSTYPE" = "noformat" ]; then
        HOMETEXT=$"$HOMEPART will not be formatted, but will be used as /home"
    fi
}

GrubLoc(){
    # Return global variables GRUBLOCTEXT and GRUBLOC
    GRUBLOCTEST="$1"
    TARGETPART="$2"
    PARTDRIVE="$3"
    
    if [ "$GRUBLOCTEST" = "root" ]; then
        GRUBLOCTEXT=$"root partition of $TARGETPART"
        GRUBLOC="/dev/$TARGETPART"
    elif [ "$GRUBLOCTEST" = "rootmbr" ]; then
        GRUBLOCTEXT=$"root partition mbr of $TARGETPART"
        GRUBLOC="/dev/$PARTDRIVE"
    else
        GRUBLOCTEXT=$"mbr of $GRUBLOCTEST"
        GRUBLOC="/dev/$GRUBLOCTEST"
    fi
}

ExitingInstallerNow(){
    # GUI MODE Quiting
    $DIALOG $TITLE"$TITLETEXT" $MSGBOX $TEXT"$ExitingInstaller"
    exit 1
}

# TEXT MODE START ##############################################################
if [ "$GUI" = "" ]; then
    #inform them what this is and ask if they want to continue

    $DIALOG $TITLE"$TITLETEXT" $YESNO $TEXT"$ThisIsTheInstaller" $HEIGHT $WIDTH

    if [ $? != 0 ]; then
        exit 0
    fi

    $DIALOG $TITLE"$TITLETEXT" $YESNO $TEXT"$IdiomKeyboardLayout" $HEIGHT $WIDTH

    if [ $? = 0 ]; then
        dpkg-reconfigure locales
        dpkg-reconfigure console-data
        #dpkg-reconfigure console-setup
        dpkg-reconfigure keyboard-configuration
    fi

    $DIALOG $TITLE"$TITLETEXT" $MSGBOX $TEXT"$CreatePartitions" $HEIGHT $WIDTH

    #choose the drive to partition
    DRIVES=`cat /proc/partitions | grep -v loop | grep -v major | grep -v "^$" | awk '{print $4}' | grep -v "[0-9]"`

    for i in $DRIVES; do
        partdrive="$i"
        partdrivesize=`grep -m 1 "$i" /proc/partitions | awk '{print $3}'`
        partdrivemenu="$partdrivemenu $partdrive $partdrivesize"
    done

    $DIALOG $TITLE"$TITLETEXT" $MENU $TEXT"$SelectDriveToPartition" $HEIGHT $WIDTH $MENUHEIGHT $EXIT "$ExitInstaller" $partdrivemenu 2>/tmp/choice.$$

    if [ "$?" = "0" ]; then
        PARTDRIVE=`cat /tmp/choice.$$`
    else
        PARTDRIVE=$EXIT
    fi

    rm /tmp/choice.$$

    if [ "$PARTDRIVE" = $EXIT ]; then
        $DIALOG $TITLE"$TITLETEXT" $MSGBOX $TEXT"$ExitingInstaller" $HEIGHT $WIDTH
        exit 1
    fi

    $PARTITIONPROG /dev/$PARTDRIVE

    #find the swap partition
    TARGETSWAP=`fdisk -l | grep swap | awk '{print $1}' | cut -d "/" -f3`
    #TARGETSWAP=`echo $TARGETSWAP | sed -r "s/\/dev\///g"`

    for i in $TARGETSWAP; do
        swappart="$i"
        swappartsize=`grep -m 1 "$i" /proc/partitions | awk '{print $3}'`
        swappartmenu="$swappartmenu $swappart $swappartsize"
    done

    $DIALOG $TITLE"$TITLETEXT" $MENU $TEXT"$SelectSwapPartition" $HEIGHT $WIDTH $MENUHEIGHT $EXIT "$ExitInstaller" $swappartmenu 2>/tmp/choice.$$

    if [ "$?" = "0" ]; then
        SWAP=`cat /tmp/choice.$$`
    else
        SWAP=$EXIT
    fi

    rm /tmp/choice.$$

    if [ "$SWAP" = $EXIT ]; then
        $DIALOG $TITLE"$TITLETEXT" $MSGBOX $TEXT"$ExitingInstaller" $HEIGHT $WIDTH
        exit 1
    fi

    #choose the partition to install to
    PARTITIONS=`cat /proc/partitions | grep -v "loop" | grep -v "sr0" | awk '{print $4}' | grep "[0-9]"`
    PARTINSTTEMP=`echo $PARTITIONS | sed -r "s/$SWAP//"`
    PARTINST=`echo $PARTINSTTEMP`

    for i in $PARTINST; do
        tempsize=`grep -m 1 "$i" /proc/partitions | awk '{print $3}'`

        if [ "$tempsize" = "1" ]; then
            PARTINST=`echo $PARTINST | sed -r "s/$i//"`
        fi
    done

    for i in $PARTINST; do
        part="$i"
        partsize=`grep -m 1 "$i" /proc/partitions | awk '{print $3}'`
        partmenu="$partmenu $part $partsize"
    done

    $DIALOG $TITLE"$TITLETEXT" $MENU $TEXT"$SelectInstallationPartition" $HEIGHT $WIDTH $MENUHEIGHT $EXIT "$ExitInstaller" $partmenu 2>/tmp/choice.$$

    if [ "$?" = "0" ]; then
        TARGETPART=`cat /tmp/choice.$$`
    else
        TARGETPART=$EXIT
    fi

    rm /tmp/choice.$$

    if [ "$TARGETPART" = $EXIT ]; then
        $DIALOG $TITLE"$TITLETEXT" $MSGBOX $TEXT"$ExitingInstaller" $HEIGHT $WIDTH
        exit 1
    fi

    #choose filesystem type
    $DIALOG $TITLE"$TITLETEXT" $MENU $TEXT"$SelectRootFileSystem" $HEIGHT $WIDTH $MENUHEIGHT ext4 "Ext4" ext3 "Ext3" ext2 "Ext2" 2>/tmp/choice.$$

    if [ "$?" = "0" ]; then
        FSTYPE=`cat /tmp/choice.$$`
    else
        FSTYPE="ext4"
    fi

    rm /tmp/choice.$$

    HOMEINST=`echo $PARTINST | sed -r "s/$TARGETPART//"`

    for i in $HOMEINST; do
        homepart="$i"
        homepartsize=`grep -m 1 "$i" /proc/partitions | awk '{print $3}'`
        homepartmenu="$homepartmenu $homepart $homepartsize"
    done

    $DIALOG $TITLE"$TITLETEXT" $MENU $TEXT"$SelectHomePartition" $HEIGHT $WIDTH $MENUHEIGHT root "$PutHomeInRootPartition" $homepartmenu 2>/tmp/choice.$$

    if [ "$?" = "0" ]; then
        HOMEPART=`cat /tmp/choice.$$`
    else
        HOMEPART="root"
    fi

    rm /tmp/choice.$$

    if [ "$HOMEPART" != "root" ]; then
        #choose filesystem type
        $DIALOG $TITLE"$TITLETEXT" $MENU $TEXT"$SelectHomeFileSystem" $HEIGHT $WIDTH $MENUHEIGHT noformat "$DontFormatHomePartition" ext4 "Ext4" ext3 "Ext3" ext2 "Ext2" 2>/tmp/choice.$$

        if [ "$?" = "0" ]; then
            HFSTYPE=`cat /tmp/choice.$$`
        else
            HFSTYPE="ext4"
        fi
            rm /tmp/choice.$$
    fi

    # "NOCONFIGS=\"user-setup" means it is backup mode
    # "" means it is dist mode
    testmode=`grep "NOCONFIGS=\"user-setup" /etc/live/config.conf`

    if [ "$testmode" = "" ]; then
        #root password entry section
        TARGETROOTPASS="1"
        TARGETROOTPASS2="2"

        while [ "$TARGETROOTPASS" != "$TARGETROOTPASS2" ]; do
            $DIALOG $TITLE"$TITLETEXT" $PASSWORD $TEXT$"Enter the root password." $HEIGHT $WIDTH 2>/tmp/choice.$$

            if [ "$?" = "0" ]; then
                TARGETROOTPASS=`cat /tmp/choice.$$`
            else
                exit 1
            fi

            rm /tmp/choice.$$

            $DIALOG $TITLE"$TITLETEXT" $PASSWORD $TEXT$"Enter the root password again." $HEIGHT $WIDTH 2>/tmp/choice.$$

            if [ "$?" = "0" ]; then
                TARGETROOTPASS2=`cat /tmp/choice.$$`
            else
                exit 1
            fi

            rm /tmp/choice.$$

            if [ "$TARGETROOTPASS" != "$TARGETROOTPASS2" ]; then
                $DIALOG $TITLE"$TITLETEXT" $MSGBOX $TEXT"$PasswordsDontMatch" $HEIGHT $WIDTH
            fi
        done

        rm /tmp/choice.$$

        #username input secton

        $DIALOG $TITLE"$TITLETEXT" $ENTRY $TEXT$"Enter the full name of the new user to be configured on the installed system." $HEIGHT $WIDTH 2>/tmp/choice.$$

        if [ "$?" = "0" ]; then
            TARGETUSERFULLNAME=`cat /tmp/choice.$$`
        else
            exit 1
        fi

        rm /tmp/choice.$$

        $DIALOG $TITLE"$TITLETEXT" $ENTRY $TEXT$"Enter the username of the new user to be configured on the installed system.\nLowercase letters only." $HEIGHT $WIDTH 2>/tmp/choice.$$

        if [ "$?" = "0" ]; then
            TARGETUSER=`cat /tmp/choice.$$`
        else
            exit 1
        fi

        rm /tmp/choice.$$

        #make sure its all lowercase just in case
        TARGETUSER="`echo $TARGETUSER | awk '{print tolower ($0)}'`"

        #password entry section

        TARGETPASS="1"
        TARGETPASS2="2"

        while [ "$TARGETPASS" != "$TARGETPASS2" ]; do
            $DIALOG $TITLE"$TITLETEXT" $PASSWORD $TEXT$"Enter a password for $TARGETUSER." $HEIGHT $WIDTH 2>/tmp/choice.$$

            if [ "$?" = "0" ]; then
                TARGETPASS=`cat /tmp/choice.$$`
            else
                exit 1
            fi

            rm /tmp/choice.$$

            $DIALOG $TITLE"$TITLETEXT" $PASSWORD $TEXT$"Retype the password of $TARGETUSER." $HEIGHT $WIDTH 2>/tmp/choice.$$

            if [ "$?" = "0" ]; then
                TARGETPASS2=`cat /tmp/choice.$$`
            else
                exit 1
            fi

            rm /tmp/choice.$$

            if [ "$TARGETPASS" != "$TARGETPASS2" ]; then
                $DIALOG $TITLE"$TITLETEXT" $MSGBOX $TEXT"$PasswordsDontMatch" $HEIGHT $WIDTH
            fi
        done

        rm /tmp/choice.$$
    fi


    #hostname setup
    $DIALOG $TITLE"$TITLETEXT" $ENTRY $TEXT$"Enter the hostname of the system to be installed" $HEIGHT $WIDTH 2>/tmp/choice.$$

    if [ "$?" = "0" ]; then
        TARGETHOSTNAME=`cat /tmp/choice.$$`
    else
        exit 1
    fi

    rm /tmp/choice.$$

    #grub location

    GrubSelectText() {
        ## Blank the array in case this function is being rerun

        GrubMenu=()

        Drives=$(cat /proc/partitions | grep -v loop | grep -v "Extended" | grep -v "extended" | grep -v "swap" | grep -v "Swap" | grep -v "Hidden" | grep -v major | grep -v "^$" | awk '{ print $4}')

        for i in $Drives; do
            PartDrive="$i"

            if [ "$(echo "$PartDrive" | grep [0-9] )" = "" ]; then
                GrubMenu=("${GrubMenu[@]}" "$PartDrive" "$DiskMBR")
            fi
        done

        GrubMenu=( "${GrubMenu[@]}" "root" "$RootPartition" "rootmbr" "$RootMBRPartition" )

        #grub location
        $DIALOG $TITLE"$TITLETEXT" $MENU $TEXT"$SelectWhereInstallGrub" $HEIGHT $WIDTH $MENUHEIGHT "${GrubMenu[@]}" 2>/tmp/choice.$$

        if [ "$?" = "0" ]; then
            GRUBLOCTEST=`cat /tmp/choice.$$`
        elif [ "$GRUBLOCTEST" = "" ]; then
            GrubSelectText
            exit 0
        fi

        rm /tmp/choice.$$

        GrubLoc $GRUBLOCTEST $TARGETPART $PARTDRIVE
    }

    GrubSelectText # call above function

    #dpkg-reconfigure tzdata
    #Timezone setting

    $DIALOG $TITLE"$TITLETEXT" $YESNO $TEXT"$SystemClockSetup" $HEIGHT $WIDTH

    if [ $? = 0 ]; then
        if [ "$(grep "UTC" /etc/adjtime)" != "" ]; then
            sed -i -e "s|UTC|LOCALTIME|g" /etc/adjtime
        fi
    else
        if [ "$(grep "LOCALTIME" /etc/adjtime)" != "" ]; then
            sed -i -e "s|LOCALTIME|UTC|g" /etc/adjtime
        fi
    fi

    cat /usr/share/zoneinfo/zone.tab | awk '{print $3}' | grep "/" | sort > /tmp/remastersys.zoneinfo

    for i in `cat /tmp/remastersys.zoneinfo`; do
        ZONES="$ZONES $i Timezone"
    done

    rm /tmp/remastersys.zoneinfo

    $DIALOG $TITLE"$TITLETEXT" $MENU $TEXT"$SelectTimeZone" $HEIGHT $WIDTH $MENUHEIGHT $EXIT "$ExitInstaller" $ZONES 2>/tmp/choice.$$

    if [ "$?" = "0" ]; then
        ZONESINFO=`cat /tmp/choice.$$`
    else
        ZONESINFO=$EXIT
    fi

    rm /tmp/choice.$$

    if [ "$ZONESINFO" = $EXIT ]; then
        $DIALOG $TITLE"$TITLETEXT" $MSGBOX $TEXT"$ExitingInstaller" $HEIGHT $WIDTH
        exit 1
    fi

    echo "$ZONESINFO" > /etc/timezone

    cp /usr/share/zoneinfo/$ZONESINFO /etc/localtime

    #$SETLOCALE
    #$SETCONSOLEDATA
    #$SETXSERVER

    HomeText "$HOMEPART" "$HFSTYPE"
    
    ConfirmDist=$"New user: $TARGETUSER\nPartition: $TARGETPART\nFile System: $FSTYPE\nSwap Partition: $SWAP\nInstall GRUB on the: $GRUBLOCTEXT"
    ConfirmBackup=$"Backup Installation Partition: $TARGETPART\nFile System: $FSTYPE\nInstall GRUB on the: $GRUBLOCTEXT"

    if [ "$testmode" = "" ]; then
        $DIALOG $TITLE"$TITLETEXT" $YESNO $TEXT"$PleaseConfirm""$ConfirmDist""$Proceed" $HEIGHT $WIDTH

        if [ $? != 0 ]; then
            exit 0
        fi
    else
        $DIALOG $TITLE"$TITLETEXT" $YESNO $TEXT"$PleaseConfirm""$ConfirmBackup""$Proceed" $HEIGHT $WIDTH

        if [ $? != 0 ]; then
            exit 0
        fi
    fi

################################################################ TEXT MODE END #

else

# GUI MODE START ###############################################################

    if [ "$testyad" = "" ]; then
        xmessage $"Yad not found. You can still use the installer in text-mode by typing \"sudo remastersys-installer\" in a terminal."
        exit 1
    fi
    
    #inform them what this is and ask if they want to continue
    $DIALOG $TITLE"$TITLETEXT" $YESNO $TEXT"$ThisIsTheInstaller"

    if [ $? != 0 ]; then
        exit 0
    fi

    FRONTTEST=`cat /etc/X11/default-display-manager | grep kdm`

    if [ "$FRONTTEST" = "" ]; then
        FRONTEND="gnome"
    else
        FRONTEND="kde"
    fi

    $DIALOG $TITLE"$TITLETEXT" $YESNO $TEXT"$IdiomKeyboardLayout"

    if [ $? = 0 ]; then
        dpkg-reconfigure -f $FRONTEND locales
        dpkg-reconfigure -f $FRONTEND console-data
        #dpkg-reconfigure -f $FRONTEND console-setup
        dpkg-reconfigure -f $FRONTEND keyboard-configuration
    fi

    #fix for gparted being inhibited by udisks-daemon
    killall -KILL udisks-daemon

    $DIALOG $TITLE"$TITLETEXT" $MSGBOX $TEXT"$CreatePartitions"

    #choose the drive to partition
    DRIVES=`cat /proc/partitions | grep -v loop | grep -v major | grep -v "^$" | awk '{print $4}' | grep -v "[0-9]"`

    for i in $DRIVES; do
        partdrive="$i"
        partdrivesize=`grep -m 1 "$i" /proc/partitions | awk '{print $3}'`
        partdrivemenu="$partdrivemenu $partdrive $partdrivesize"
    done

    PARTDRIVE=""
    while [ "$PARTDRIVE" = "" ]; do
        PARTDRIVE=`$DIALOGMENU $TITLE"$TITLETEXT" $MENU $TEXT"$SelectDriveToPartition" $EXIT "$ExitInstaller" $partdrivemenu`
    done
    
    if [ "$?" != "0" ]; then
        ExitingInstallerNow
    fi

    PARTDRIVE=`echo $PARTDRIVE | cut -d "|" -f 1`

    if [ "$PARTDRIVE" = $EXIT ]; then
        ExitingInstallerNow
    fi

    $PARTITIONPROG /dev/$PARTDRIVE

    #find the swap partition
    TARGETSWAP=`fdisk -l | grep swap | awk '{print $1}' | cut -d "/" -f3`
    #TARGETSWAP=`echo $TARGETSWAP | sed -r "s/\/dev\///g"`
    for i in $TARGETSWAP; do
        swappart="$i"
        swappartsize=`grep -m 1 "$i" /proc/partitions | awk '{print $3}'`
        swappartmenu="$swappartmenu $swappart $swappartsize"
    done

    SWAP=""
    while [ "$SWAP" = "" ]; do
        SWAP=`$DIALOGMENU $TITLE"$TITLETEXT" $MENU $TEXT"$SelectSwapPartition" $EXIT "$ExitInstaller" $swappartmenu`
    done
    
    if [ "$?" != "0" ]; then
        ExitingInstallerNow
    fi

    SWAP=`echo $SWAP | cut -d "|" -f 1`

    if [ "$SWAP" = $EXIT ]; then
        ExitingInstallerNow
    fi

    #choose the partition to install to
    PARTITIONS=`cat /proc/partitions | grep -v "loop" | grep -v "sr0" | awk '{print $4}' | grep "[0-9]"`
    PARTINSTTEMP=`echo $PARTITIONS | sed -r "s/$SWAP//"`
    PARTINST=`echo $PARTINSTTEMP`
    for i in $PARTINST; do
        tempsize=`grep -m 1 "$i" /proc/partitions | awk '{print $3}'`
        if [ "$tempsize" = "1" ]; then
            PARTINST=`echo $PARTINST | sed -r "s/$i//"`
        fi
    done

    for i in $PARTINST; do
        part="$i"
        partsize=`grep -m 1 "$i" /proc/partitions | awk '{print $3}'`
        partmenu="$partmenu $part $partsize"
    done

    TARGETPART=""
    while [ "$TARGETPART" = "" ]; do
        TARGETPART=`$DIALOGMENU $TITLE"$TITLETEXT" $MENU $TEXT"$SelectInstallationPartition" $EXIT "$ExitInstaller" $partmenu`
    done
    
    if [ "$?" != "0" ]; then
        ExitingInstallerNow
    fi

    TARGETPART=`echo $TARGETPART | cut -d "|" -f 1`

    if [ "$TARGETPART" = $EXIT ]; then
        ExitingInstallerNow
    fi

    FSTYPE=""
    while [ "$FSTYPE" = "" ]; do
        FSTYPE=`$DIALOGMENU $TITLE"$TITLETEXT" $MENU $TEXT"$SelectRootFileSystem" ext4 "Ext4" ext3 "Ext3" ext2 "Ext2"`
    done
    
    if [ "$?" != "0" ]; then
        ExitingInstallerNow
    fi

    FSTYPE=`echo $FSTYPE | cut -d "|" -f 1`

    HOMEINST=`echo $PARTINST | sed -r "s/$TARGETPART//"`
    for i in $HOMEINST; do
        homepart="$i"
        homepartsize=`grep -m 1 "$i" /proc/partitions | awk '{print $3}'`
        homepartmenu="$homepartmenu $homepart $homepartsize"
    done

    HOMEPART=""
    while [ "$HOMEPART" = "" ]; do
        HOMEPART=`$DIALOGMENU $TITLE"$TITLETEXT" $MENU $TEXT"$SelectHomePartition" root "$PutHomeInRootPartition" $homepartmenu`
    done
    
    if [ "$?" != "0" ]; then
        ExitingInstallerNow
    fi

    HOMEPART=`echo $HOMEPART | cut -d "|" -f 1`

    if [ "$HOMEPART" != "root" ]; then
        HFSTYPE=""
        while [ "$HFSTYPE" = "" ]; do
            HFSTYPE=`$DIALOGMENU $TITLE"$TITLETEXT" $MENU $TEXT"$SelectHomeFileSystem" noformat "$DontFormatHomePartition" ext4 "Ext4" ext3 "Ext3" ext2 "Ext2"`
        done
    fi

    HFSTYPE=`echo $HFSTYPE | cut -d "|" -f 1`

    # "NOCONFIGS=\"user-setup" means it is backup mode
    # "" means it is dist mode
    testmode=`grep "NOCONFIGS=\"user-setup" /etc/live/config.conf`

    if [ "$testmode" = "" ]; then

        while [ "$PASSOK" != "Yes" ]; do
            PSWD1=$"Password for root"
            PSWD2=$"Password for root (retype)"
            PSWD3=$"New user's full name"
            PSWD4=$"New user's username"
            PSWD5=$"Password for new user"
            PSWD6=$"Password for new user (retype)"
            PSWD7=$"Hostname for the computer"

            CHOICES=`$DIALOGMENU $TITLE"$TITLETEXT" --form \
            --field="$PSWD1":H \
            --field="$PSWD2":H \
            --field="$PSWD3" \
            --field="$PSWD4" \
            --field="$PSWD5":H \
            --field="$PSWD6":H \
            --field="$PSWD7"`

            if [ "$?" = "0" ]; then
                TARGETROOTPASS=`echo $CHOICES | cut -d "|" -f 1`
                TARGETROOTPASS2=`echo $CHOICES | cut -d "|" -f 2`
                TARGETUSERFULLNAME=`echo $CHOICES | cut -d "|" -f 3`
                TARGETUSER=`echo $CHOICES | cut -d "|" -f 4`
                TARGETPASS=`echo $CHOICES | cut -d "|" -f 5`
                TARGETPASS2=`echo $CHOICES | cut -d "|" -f 6`
                TARGETHOSTNAME=`echo $CHOICES | cut -d "|" -f 7`
            else
                ExitingInstallerNow
            fi

            [ "$TARGETROOTPASS" != "" ] && \
            [ "$TARGETROOTPASS" = "$TARGETROOTPASS2" ] && \
            [ "$TARGETUSERFULLNAME" != "" ] && \
            [ "$TARGETUSER" != "" ] && \
            [ "$TARGETUSER" != "$LIVE_USERNAME" ] && \
            [ "$TARGETPASS" != "" ] && \
            [ "$TARGETPASS" = "$TARGETPASS2" ] && \
            [ "$TARGETROOTPASS" != "$TARGETPASS" ] && \
            [ "$TARGETHOSTNAME" != "" ] && \
            PASSOK="Yes"

            [ "$TARGETROOTPASS" = "" ] && $DIALOG $TITLE"$TITLETEXT" $MSGBOX $TEXT$"Root password in blank."

            [ "$TARGETROOTPASS" != "$TARGETROOTPASS2" ] && $DIALOG $TITLE"$TITLETEXT" $MSGBOX $TEXT$"Passwords entered for Root do not match."

            [ "$TARGETUSERFULLNAME" = "" ] && $DIALOG $TITLE"$TITLETEXT" $MSGBOX $TEXT$"User's full name in blank."

            [ "$TARGETUSER" = "" ] && $DIALOG $TITLE"$TITLETEXT" $MSGBOX $TEXT$"Blank username."

            [ "$TARGETUSER" = "$LIVE_USERNAME" ] && $DIALOG $TITLE"$TITLETEXT" $MSGBOX $TEXT$"Username cannot be the same as the Live CD username."

            [ "$TARGETPASS" = "" ] && $DIALOG $TITLE"$TITLETEXT" $MSGBOX $TEXT$"Blank user password."

            [ "$TARGETPASS" != "$TARGETPASS2" ] && $DIALOG $TITLE"$TITLETEXT" $MSGBOX $TEXT$"Passwords entered for the user do not match."

            [ "$TARGETROOTPASS" = "$TARGETPASS" ] && $DIALOG $TITLE"$TITLETEXT" $MSGBOX $TEXT$"Root and user passwords are the same.\n\nUse different passwords."

            [ "$TARGETHOSTNAME" = "" ] && $DIALOG $TITLE"$TITLETEXT" $MSGBOX $TEXT$"Blank hostname."

        done
    fi

    #hostname setup
    #TARGETHOSTNAME=`$DIALOG $TITLE"$TITLETEXT" $ENTRY $TEXT"Please enter the hostname for the installed system."`

    #grub location
    GrubSelectGUI () {
        GrubMenu=()

        Drives=$(cat /proc/partitions | grep -v loop | grep -v "Extended" | grep -v "extended" | grep -v "swap" | grep -v "Swap" | grep -v "Hidden" | grep -v major | grep -v "^$" | awk '{ print $4}')

        for i in $Drives; do
            PartDrive="$i"

            if [ "$(echo "$PartDrive" | grep [0-9] )" = "" ]; then
                GrubMenu=("${GrubMenu[@]}" "$PartDrive" "$DiskMBR")
            fi
        done

        GrubMenu=( "${GrubMenu[@]}" "root" "$RootPartition" "rootmbr" "$RootMBRPartition" )

        #grub location
        GRUBLOCTEST=$($DIALOGMENU $TITLE"$TITLETEXT" $MENU $TEXT"$SelectWhereInstallGrub" "${GrubMenu[@]}")

        ret="$?"

        if [ "$ret" = "252" ]; then
            GrubSelectGUI
            exit 0
        elif [ "$GRUBLOCTEST" = "" ]; then
            GrubSelectGUI
            exit 0
        fi

        GRUBLOCTEST=$(echo "$GRUBLOCTEST" | awk -F '|' '{print $1}')
        
        GrubLoc $GRUBLOCTEST $TARGETPART $PARTDRIVE
    }

    GrubSelectGUI # call above function

    #Timezone setting

    $DIALOG $TITLE"$TITLETEXT" $YESNO $TEXT"$SystemClockSetup"

    if [ $? = 0 ]; then
        if [ "$(grep "UTC" /etc/adjtime)" != "" ]; then
            sed -i -e "s|UTC|LOCALTIME|g" /etc/adjtime
        fi
    else
        if [ "$(grep "LOCALTIME" /etc/adjtime)" != "" ]; then
            sed -i -e "s|LOCALTIME|UTC|g" /etc/adjtime
        fi
    fi

    cat /usr/share/zoneinfo/zone.tab | awk '{print $3}' | grep "/" | sort > /tmp/remastersys.zoneinfo

    for i in `cat /tmp/remastersys.zoneinfo`; do
        ZONES="$ZONES $i Timezone"
    done

    rm /tmp/remastersys.zoneinfo

    ZONESINFO=""

    while [ "$ZONESINFO" = "" ]; do
        ZONESINFO=`$DIALOGMENU $TITLE"$TITLETEXT" $MENU $TEXT"$SelectTimeZone" $EXIT "$ExitInstaller" $ZONES`
    done
    
    if [ "$?" != "0" ]; then
        ExitingInstallerNow
    fi

    ZONESINFO=`echo $ZONESINFO | cut -d "|" -f 1`

    if [ "$ZONESINFO" = $EXIT ]; then
        ExitingInstallerNow
    fi

    echo "$ZONESINFO" > /etc/timezone

    cp /usr/share/zoneinfo/$ZONESINFO /etc/localtime

    #xterm -e dpkg-reconfigure tzdata
    #if [ "$1" = "intl" ]; then
    #xterm -e $SETLOCALE
    #xterm -e $SETCONSOLEDATA
    #xterm -e $SETXSERVER
    #fi

    HomeText "$HOMEPART" "$HFSTYPE"
    
    ConfirmDist=$"New user is: $TARGETUSER\nPartition: $TARGETPART\nFile System: $FSTYPE\nSwap Partition: $SWAP\nInstall GRUB on the: $GRUBLOCTEXT"
    ConfirmBackup=$"Backup Installation Partition: $TARGETPART\nFile System is: $FSTYPE\nInstall GRUB on the: $GRUBLOCTEXT"

    if [ "$testmode" = "" ]; then
        $DIALOG $TITLE"$TITLETEXT" $YESNO $TEXT"$PleaseConfirm""$ConfirmDist""$Proceed"

        if [ $? != 0 ]; then
            ExitingInstallerNow
        fi
    else
        $DIALOG $TITLE"$TITLETEXT" $YESNO $TEXT"$PleaseConfirm""$ConfirmBackup""$Proceed"

        if [ $? != 0 ]; then
            ExitingInstallerNow
        fi
    fi

fi
################################################################# GUI MODE END #

########################
# INSTALL TO HARD DISK #
########################

UmountingFormatingTARGETPART=$"Unmounting and formatting the partition we are going to use."
MountingTARGET=$"Mounting the TARGET partition now."
RUNsetupSWAP=$"Configuring SWAP... Please wait.\n"
RUNformatTARGET=$"Formatting $TARGETPART... Please wait.\n"
RUNformatHOME=$"Formatting $HOME... Please wait.\n"
RUNcopyToDISK=$"Copying files to disk... Please wait.\n"
RUNpostINSTALL=$"Performing post-installation steps... Please wait.\n"
RUNsetupGRUB=$"Installing and configuring grub... Please wait.\n"

if [ "$GUI" != "" ]; then
    progressbar $RUNsetupSWAP &
fi

sleep 2
echo $RUNsetupSWAP
mkswap /dev/$SWAP
swapon /dev/$SWAP

killtail(){
    if [ "$GUI" != "" ]; then
        killall -KILL tail
    fi
}
killtail

if [ "$GUI" != "" ]; then
    progressbar $RUNformatTARGET &
fi

echo $RUNformatTARGET

# Preserve kernel options in the new grub system
NewGrubDefLine="$(cat /proc/cmdline | awk -F 'config ' '{print $2}' | awk -F ' BOOT' '{print $1}')"

OldGrubDefLine=$(grep -B 0  "GRUB_CMDLINE_LINUX_DEFAULT=" /etc/default/grub)
OldGrubLine=$(grep -B 0  "GRUB_CMDLINE_LINUX=" /etc/default/grub)
sed -i -e "s/$OldGrubDefLine/GRUB_CMDLINE_LINUX_DEFAULT=\"$NewGrubDefLine\"/g" /etc/default/grub
sed -i -e "s/$OldGrubLine/GRUB_CMDLINE_LINUX=\"\"/g" /etc/default/grub

# Make the filesystem and mount the partition on /TARGET
if [ "`mount | grep $TARGETPART`" ]; then
    echo $UmountingFormatingTARGETPART
    umount /dev/$TARGETPART
fi

mke2fs -Ft $FSTYPE /dev/$TARGETPART
mkdir -p /TARGET
sleep 2
echo $MountingTARGET
mount /dev/$TARGETPART /TARGET -o rw
sleep 2
echo $"Using tune2fs to prevent forced checks on boot."
tune2fs -c 0 -i 0 /dev/$TARGETPART
rm -rf "/TARGET/lost+found"

killtail

if [ "$HOMEPART" != "root" ]; then
    if [ "$HFSTYPE" != "noformat" ]; then
        if [ "$GUI" != "" ]; then
            progressbar $RUNformatHOME &
        fi

        echo $RUNformatHOME

        if [ "`mount | grep $HOMEPART`" ]; then
            echo $UmountingFormatingTARGETPART
            umount /dev/$HOMEPART
        fi

        mke2fs -Ft $HFSTYPE /dev/$HOMEPART
    fi

    echo $MountingTARGET
    mkdir -p /TARGET/home
    mount /dev/$HOMEPART /TARGET/home -o rw
    tune2fs -c 0 -i 0 /dev/$HOMEPART
    rm -rf "/TARGET/home/lost+found"
    sleep 2
    
    # Get fs type for home partition in case the user chose not to format
    if [ "$HFSTYPE" = "noformat" ]; then
        HFSTYPE=`mount | grep "/dev/$HOMEPART" | awk '{print $5}'`
    fi

    if [ "$GUI" != "" ]; then
        killall -KILL tail
    fi
fi

# Get the cdrom device for fstab
# TARGETCDROM=`cat /proc/mounts | grep "/live/image" | awk '{print $1}'`
TARGETCDROM="/dev/cdrom"

sleep 1

killtail

# "NOCONFIGS=\"user-setup" means it is backup mode
# "" means it is dist mode
testmode=`grep "NOCONFIGS=\"user-setup" /etc/live/config.conf`

if [ "$testmode" = "" ]; then
    LIVEMODE="DIST"
else
    LIVEMODE="BACKUP"
fi

cat > /var/log/remastersys-installer.log <<FOO
==============================
Remastersys-Installer log file
==============================
LIVEMODE=$LIVEMODE
GUI=$GUI
TARGETUSER=$TARGETUSER
TARGETHOSTNAME=$TARGETHOSTNAME
SWAP=$SWAP
TARGETPART=$TARGETPART
FSTYPE=$FSTYPE
HOMEPART=$HOMEPART
HFSTYPE=$HFSTYPE
GRUBLOC=$GRUBLOC
FOO

stripe="=============================================================="
echo -e "$stripe\nMOUNTS\n$stripe" >> /var/log/remastersys-installer.log
mount >> /var/log/remastersys-installer.log
echo -e  "$stripe\nFDISK listing\n$stripe" >> /var/log/remastersys-installer.log
fdisk -l >> /var/log/remastersys-installer.log
echo -e "$stripe\nlive config listing\n$stripe" >> /var/log/remastersys-installer.log
cat /etc/live/config.conf >> /var/log/remastersys-installer.log
echo -e "$stripe\nEND OF LOG" >> /var/log/remastersys-installer.log

if [ "$GUI" != "" ]; then
    progressbar $RUNcopyToDISK &
fi

# Copy the live system to the hd
echo $RUNcopyToDISK

if [ "$HFSTYPE" = "noformat" ]; then
    rsync -a / /TARGET --ignore-existing --exclude=/{TARGET,home,live,cdrom,mnt,proc,run,sys,media}
else
    rsync -a / /TARGET --ignore-existing --exclude=/{TARGET,live,cdrom,mnt,proc,run,sys,media}
fi

mkdir -p /TARGET/{proc,mnt,run,sys,media/cdrom}

# Remove the live installer from the desktop of /etc/skel/Desktop
if [ -f /TARGET/etc/skel/Desktop/remastersys-installer.desktop -o -f /TARGET/etc/skel/Desktop/remastersys-installer-ked.desktop ]; then
    rm -f /TARGET/etc/skel/Desktop/remastersys-installer*.desktop
fi

echo $"File copy completed."

killtail

if [ "$GUI" != "" ]; then
    progressbar $RUNpostINSTALL &
fi

echo $RUNpostINSTALL

# Prepare the chroot environment for some post install changes
mount -o bind /proc /TARGET/proc
mount -o bind /dev /TARGET/dev
mount -o bind /sys /TARGET/sys
rm -f /TARGET/etc/fstab
rm -f /TARGET/etc/profile.d/zz-live.sh

# Create the new fstab
if [ "$HOMEPART" = "root" ]; then
    cat > /TARGET/etc/fstab <<FOO
# /etc/fstab: static file system information.
#
# <file system> <mount point>   <type>  <options>       <dump>  <pass>

proc /proc proc defaults 0 0
# /dev/$TARGETPART
/dev/$TARGETPART / $FSTYPE relatime,errors=remount-ro 0 1
# /dev/$SWAP
/dev/$SWAP none swap sw 0 0
# cdrom
$TARGETCDROM /media/cdrom udf,iso9660 user,noauto,exec,utf8 0 0
FOO
else
    cat > /TARGET/etc/fstab <<FOO
# /etc/fstab: static file system information.
#
# <file system> <mount point>   <type>  <options>       <dump>  <pass>

proc /proc proc defaults 0 0
# /dev/$TARGETPART
/dev/$TARGETPART / $FSTYPE relatime,errors=remount-ro 0 1
# /dev/$HOMEPART home
/dev/$HOMEPART /home $HFSTYPE relatime 0 0
# /dev/$SWAP
/dev/$SWAP none swap sw 0 0
# cdrom
$TARGETCDROM /media/cdrom udf,iso9660 user,noauto,exec,utf8 0 0
FOO
fi

# remove diverted update-initramfs as live-initramfs makes it a dummy file when booting the livecd
if [ -f /TARGET/usr/sbin/update-initramfs.debian ]; then
    rm -f /TARGET/usr/sbin/update-initramfs
fi

# remove diverted update-notifier as it is disabled by live-config
if [ -f /TARGET/usr/lib/update-notifier/apt-check.debian ]; then
    rm -f /TARGET/usr/lib/update-notifier/apt-check
fi

# remove diverted anacron as it is disabled by live-config
if [ -f /TARGET/usr/sbin/anacron.debian ]; then
    rm -f /TARGET/usr/sbin/anacron
fi

# fix adept_notifier by copying the file we saved when remastersys first ran as live-initramfs removes it
if [ -f /TARGET/etc/remastersys/adept_notifier_auto.desktop ]; then
    mv /TARGET/etc/remastersys/adept_notifier_auto.desktop /TARGET/usr/share/autostart/adept_notifier_auto.desktop
fi

# copy trackerd stuff as live-initramfs disables it
if [ -f /TARGET/etc/remastersys/tracker-applet.desktop ]; then
    mv /TARGET/etc/remastersys/tracker-applet.desktop /TARGET/etc/xdg/autostart/tracker-applet.desktop
fi

if [ -f /TARGET/etc/remastersys/trackerd.desktop.xdg ]; then
    mv /TARGET/etc/remastersys/trackerd.desktop.xdg /TARGET/etc/xdg/autostart/trackerd.desktop
fi

if [ -f /TARGET/etc/remastersys/trackerd.desktop.share ]; then
    mv /TARGET/etc/remastersys/trackerd.desktop.share /TARGET/usr/share/autostart/trackerd.desktop
fi

#restore original inittab as live-initramfs changes it
cp /TARGET/usr/share/sysvinit/inittab /TARGET/etc/inittab

#check if this is a backup livecd or a dist livecd
if [ "$TARGETUSER" != "" ]; then
    echo "$TARGETHOSTNAME" > /TARGET/etc/hostname
    echo "127.0.0.1 localhost" > /TARGET/etc/hosts
    echo "127.0.0.1 $TARGETHOSTNAME" >> /TARGET/etc/hosts
    touch /TARGET/etc/resolv.conf

    #remove autologin from livecd on installed system

    #gdm and gdm3 section
    if [ -f /TARGET/etc/gdm/gdm.conf ]; then
        sed -i -e 's/AutomaticLogin/#AutomaticLogin/g' /TARGET/etc/gdm/gdm.conf
        sed -i -e 's/TimedLogin/#TimedLogin/g' /TARGET/etc/gdm/gdm.conf
    fi

    if [ -f /TARGET/etc/gdm3/daemon.conf ]; then
        sed -i -e 's/AutomaticLogin/#AutomaticLogin/g' /TARGET/etc/gdm3/daemon.conf
        sed -i -e 's/TimedLogin/#TimedLogin/g' /TARGET/etc/gdm3/daemon.conf
    fi

    #kde3 and kde4 section
    if [ -f /TARGET/etc/default/kdm.d/live-autologin ]; then
        rm -f /TARGET/etc/default/kdm.d/live-autologin
    fi
    
    if [ -f /TARGET/etc/kde3/kdm/kdmrc ]; then
        sed -i -e 's/AutoLogin/#AutoLogin/g' /TARGET/etc/kde3/kdm/kdmrc
        sed -i -e 's/AutoReLogin/#AutoReLogin/g' /TARGET/etc/kde3/kdm/kdmrc
    fi
    
    if [ -f /TARGET/etc/kde4/kdm/kdmrc ]; then
        sed -i -e 's/AutoLogin/#AutoLogin/g' /TARGET/etc/kde4/kdm/kdmrc
        sed -i -e 's/AutoReLogin/#AutoReLogin/g' /TARGET/etc/kde4/kdm/kdmrc
    fi

    #slim section
    if [ -f /TARGET/etc/slim.conf ]; then
        sed -i -e 's/auto_login/#auto_login/g' /TARGET/etc/slim.conf
        sed -i -e 's/default_user/#default_user/g' /TARGET/etc/slim.conf
    fi

    #lxdm section
    if [ -f /TARGET/etc/lxdm/lxdm.conf ]; then
        sed -i -e 's/autologin/#autologin/g' /TARGET/etc/lxdm/lxdm.conf
        sed -i -e 's/session/#session/g' /TARGET/etc/lxdm/lxdm.conf
    fi

    #lightdm section
    if [ -f /TARGET/etc/lightdm/lightdm.conf ]; then
        sed -i -e 's/autologin/#autologin/g' /TARGET/etc/lightdm/lightdm.conf
    fi

    #cleanup live polkit file from new install
    rm -f /TARGET/var/lib/polkit-1/localauthority/10-vendor.d/10-live-cd.pkla

    if [ -f /etc/remastersys/remastersys-installer.conf ]; then
        . /etc/remastersys/remastersys-installer.conf
    fi
    
    if [ "$DEFAULTGROUPS" = "" ]; then
        DEFAULTGROUPS="audio,cdrom,dialout,floppy,video,plugdev,netdev,sudo"
    fi

    cat > /TARGET/bin/tempinstallerscript <<FOO
#!/bin/bash

echo -e "$TARGETROOTPASS\n$TARGETROOTPASS\n" | passwd root
userdel -f -r $LIVE_USERNAME
sed -i '/$LIVE_USERNAME/d' /etc/sudoers
groupadd -g 1000 $TARGETUSER
useradd -u 1000 -g 1000 -c "$TARGETUSERFULLNAME,,," -G $DEFAULTGROUPS -s /bin/bash -m $TARGETUSER
echo -e "$TARGETPASS\n$TARGETPASS\n" | passwd $TARGETUSER
dpkg-divert --remove --rename --quiet /usr/lib/update-notifier/apt-check
dpkg-divert --remove --rename --quiet /usr/sbin/update-initramfs
dpkg-divert --remove --rename --quiet /usr/sbin/anacron
update-initramfs -t -c -k $(/bin/uname -r)
shadowconfig on
FOO
else
    #echo "$TARGETHOSTNAME" > /TARGET/etc/hostname
    #echo "127.0.0.1 localhost" > /TARGET/etc/hosts
    #echo "127.0.0.1 $TARGETHOSTNAME" >> /TARGET/etc/hosts
    #touch /TARGET/etc/resolv.conf

    cat > /TARGET/bin/tempinstallerscript <<FOO
#!/bin/bash

dpkg-divert --remove --rename --quiet /usr/lib/update-notifier/apt-check
dpkg-divert --remove --rename --quiet /usr/sbin/update-initramfs
dpkg-divert --remove --rename --quiet /usr/sbin/anacron
update-initramfs -t -c -k $(uname -r)

# return Thunar volmanrc back to normal
for i in $(ls -d /home/*); do
    if [ -f "$i/.config/Thunar/volmanrc" ]; then
        sed -i -e 's/FALSE/TRUE/g' $i/.config/Thunar/volmanrc
        cp -f $i/.config/volmanrc /root/.config/Thunar/volmanrc
    fi
done
FOO
fi

chmod 755 /TARGET/bin/tempinstallerscript
chroot /TARGET /bin/tempinstallerscript
rm /TARGET/bin/tempinstallerscript
rm -rf /TARGET/lib/live
rm -rf /TARGET/etc/live

killtail

# Setup grub

cat > /tmp/Remastersys-Grub-Install << FOO
#!/bin/bash
chroot /TARGET grub-install --force --no-floppy "$GRUBLOC"
chroot /TARGET update-grub
exit 0
FOO

chmod +x /tmp/Remastersys-Grub-Install

if [ "$GUI" != "" ]; then
    progressbar $RUNsetupGRUB &
    xterm -e /tmp/Remastersys-Grub-Install
    sleep 1
    rm -rf /tmp/Remastersys-Grub-Install
else
    echo $RUNsetupGRUB
    /tmp/Remastersys-Grub-Install
    sleep 1
    rm -rf /tmp/Remastersys-Grub-Install
fi

echo -e $"Post-installation steps completed.\n\nUnmounting the TARGET partition."
sleep 1
umount /TARGET/proc
sleep 1
umount /TARGET/dev
sleep 1
umount /TARGET/sys
sleep 1
umount /TARGET/home
sleep 1
umount /TARGET
sleep 1

killtail

$DIALOG $TITLE"$TITLETEXT" $YESNO $TEXT$"Installation is complete.\n\nIf all went well you should have your new system installed and ready to use.\n\nDo you want to reboot now to test the new system?" $HEIGHT $WIDTH

if [ $? != 0 ]; then
    exit 0
else
    reboot
fi
