#!/bin/bash
#
# Kanotix-Update-GUI
#
# written by Andreas Loibl (http://www.andreas-loibl.de)
#

VERSION="0.2.1 (17.12.2005)"
TITLE="Kanotix-Update-GUI by A.Loibl"
DIALOG="Xdialog --stdout"

KERNEL_MIRROR="http://debian.tu-bs.de/project/kanotix/kernel/"

# OFFLINE_MODE=1

# Locale laden
export TEXTDOMAINDIR="/usr/share/locale"
export TEXTDOMAIN=kanotix-update-gui

if [ $(id -u) -ne 0 ]; then
    # Nicht als root gestartet

    if [ -e "/usr/bin/kanotix-su" ]; then
        kanotix-su "$0" $@
    else
        kdesu -- "$0" $@
    fi
    exit 0
fi

# gibt den Info-Dialog aus
function infoDialog()
{
dialogMsg "Kanotix-Update-GUI

Version: $VERSION
Autor: Andreas Loibl
(http://www.andreas-loibl.de)

"$"This script is explicitely declared experimental!
I can't give any warranty!

Any use of the script is at your own risk!

For further information visit
www.andreas-loibl.de"
}

# gibt den Hilfe-Dialog aus
function helpDialog()
{
dialogMsg "Hilfe-Text fehlt noch...

Help-Text is still missing..."
}

function debug()
{
    echo "$1" 1>&2
}

# Erzeugt das InitScript
function createInitScript()
{
    # Bugfix: wenn freeze-rc.d gestartet wurde dann wird K-U-GUI nicht automatisch im RL 3 gestartet werden knnen
    REFREEZE=
    [ -e "/etc/frozen-rc.d" ] && REFREEZE=1 && unfreeze-rc.d # darum hier unfreeze-rc.d ausfhren
    update-rc.d -f kanotix-update-gui remove
    update-rc.d kanotix-update-gui stop 20 0 1 2 3 4 6 . start 20 5 .
    [ $REFREEZE ] && freeze-rc.d
    echo "$1" > /usr/share/kanotix-update-gui/type
}

# Zeigt ein Men an
function dialogMenu()
{
    MENUTEXT="$1"
    shift
    COMMAND="$DIALOG  --icon /usr/share/pixmaps/kanotix-update-gui-64x64.xpm --title \"$TITLE\" --menubox \"$MENUTEXT\" 30 40 0"
    while [ $# -gt 0 ]
    do
        COMMAND="$COMMAND \"$1\""
        shift
    done
    OUTPUT=$(eval "$COMMAND")
    RETURNCODE=$?
    echo "$OUTPUT"
    return $RETURNCODE
}

# Zeigt eine MessageBox an
function dialogMsg()
{
    COMMAND="$DIALOG --title \"$TITLE\" --msgbox \"\n$1\n\" 0 0"
    echo $(eval "$COMMAND")
}

# Zeigt eine Ja/Nein-Abfrage an
function dialogYesNo()
{
    COMMAND="$DIALOG --title \"$TITLE\" --yesno \"\n$1\n\" 0 0"
    eval "$COMMAND"
    return $?
}

# Zeigt ein Eingabefeld an
function dialogInputBox()
{
    COMMAND="$DIALOG --title \"$TITLE\" --inputbox \"\n$1\n\" 0 0 \"$2\""
    OUTPUT=$(eval "$COMMAND")
    RETURNCODE=$?
    echo "$OUTPUT"
    return $RETURNCODE
}

# Zeigt eine Auswahlliste an
function dialogRadioList()
{
    MENUTEXT="$1"
    shift
    COMMAND="$DIALOG --title \"$TITLE\" --radiolist \"\n$MENUTEXT\n\" 50 80 15"
    while [ $# -gt 0 ]
    do
        COMMAND="$COMMAND \"$1\""
        shift
    done
    OUTPUT=$(eval "$COMMAND")
    RETURNCODE=$?
    echo "$OUTPUT"
    return $RETURNCODE
}

# Zeigt eine Auswahlliste an
function dialogCheckList()
{
    MENUTEXT="$1"
    shift
    COMMAND="$DIALOG --title \"$TITLE\" --separate-output --checklist \"\n$MENUTEXT\n\" 0 0 10"
    while [ $# -gt 0 ]
    do
        COMMAND="$COMMAND \"$1\""
        shift
    done
    OUTPUT=$(eval "$COMMAND")
    RETURNCODE=$?
    echo "$OUTPUT"
    return $RETURNCODE
}

# Zeigt eine LogBox an
function dialogLogBox()
{
    COMMAND="$DIALOG --title \"$TITLE\" --logbox \"$1\" 0 0"
    echo $(eval "$COMMAND")
}

# Zeigt eine TextBox an
function dialogTextBox()
{
    COMMAND="$DIALOG --title \"$TITLE\" --no-cancel --textbox \"$1\" 30 100"
    echo $(eval "$COMMAND")
}

# Zeigt eine WaitBox an
function dialogWaitBox()
{
    $DIALOG --title "$TITLE" --backtitle $"Please wait..." --no-buttons --infobox "$1" 15 50 0
}

# Ld eine Datei herunter und zeigt einen grafischen Fortschrittsbalken an
function downloadFile()
{
    LOCAL_FILENAME="$2"
    [ -z "$LOCAL_FILENAME" ] && LOCAL_FILENAME=$(basename "$1")
    #CMD="wget -O\"$LOCAL_FILENAME\" \"$1\" 2>&1 | awk '{sub(\"200\",\"0%\"); sub(\"%\",\"\"); print \$7 | \"$DIALOG --gauge \\\"$STATUS_DOWNLOAD_FILE\n\n$1\\\" 0 0 0 2>&1 >/dev/null\"; }'"
    #eval "$CMD"
    wget -O"$LOCAL_FILENAME" "$1" 2>&1 | awk "{sub(\"200\",\"0%\"); sub(\"%\",\"\"); print \$7 | \"$DIALOG --gauge \\\""$"Downloading file""\n\n$1\\\" 0 0 0\"; }"
    RETURNCODE=${PIPESTATUS[0]}
    echo $LOCAL_FILENAME
    return $RETURNCODE
}

# Erzeugt eine temporre Datei
function createTempFile()
{
    TEMP_FILE="$(mktemp -t kugui.XXXXXX)"
    touch "$TEMP_FILE"
    chmod +x "$TEMP_FILE"
    echo "$TEMP_FILE"
}

# Lscht eine temporre Datei
function removeTempFile()
{
    [ -f "$1" ] && rm -f "$1"
}

function executeInConsole()
{
    TEMP_FILE=$(createTempFile)
    echo "#!/bin/bash" >"$TEMP_FILE"
    while [ "$1" ]
    do
        echo "$1" >>"$TEMP_FILE"
        shift
    done
    konsole --caption "Kanotix-Update-GUI" -e $TEMP_FILE
    RETURNCODE=$?
    removeTempFile "$TEMP_FILE"
    return $RETURNCODE
}

# Macht das Kernel-Update
function kernelUpdate()
{
# # Irgendetwas checken, steht so im Wiki, ich glaub das ist wichtig wenn man das Script auf einer "NichtKanotixInstallation" anwendet
# MKIMAGE_CHECK=$(grep MKIMAGE /etc/mkinitrd/mkinitrd.conf) >/dev/null
# if ! (echo $MKIMAGE_CHECK | grep "mkext2fs" >/dev/null); then
#     # Abbrechen, da irgendetwas noch nicht richtig eingestellt ist
#     dialogMsg $"Warning: the following line was found in your /etc/mkinitrd/mkinitrd.conf:""
# 
# $MKIMAGE_CHECK
# 
# "$"The Kanotix wiki claims that this is wrong and has to be repaired manually. For more information see:
# 
# http://wiki.kanotix.net/CoMa.php?CoMa=Kanotix-Kernel-UpdateEN"
#     return 1 # Kernel-Update abbrechen
# fi


# Erstmal fragen, ob die URLs manuell oder automatisch ermittelt werden sollen
dialogYesNo $"Search for newest kernel automagically?\n\n(If you select 'No' you have to enter the URLs manually)"
RET=$?
if [ $RET -eq 2 ]; then
    # Abbrechen gedrckt... also Schluss jetzt
    return 1
fi

if [ $RET -eq 1 ]; then
    # Nein gedrckt... also manuell weitermachen
    SELECTED_KERNEL_FILE=$(dialogInputBox $"Enter the URL to kernel file")
    [ $? -ne 0 ] && return 1
    SELECTED_DRIVER_FILE=$(dialogInputBox $"Enter the URL to driver file

(if you don't want to install additional drivers, select 'Cancel')")
    DL_FILES_TO_DOWNLOAD="$SELECTED_KERNEL_FILE $SELECTED_DRIVER_FILE"
else

# Ja gedrckt, also los geht's...

# Erstmal die Seite runterladen, dann die Kommentare entfernen und nach (href)="driver..." und (href)="kernel..." suchen
LIST_KUPD_FILES=$(wget -q -O - "$KERNEL_MIRROR" | sed -n -e '
/<!--/!bc
:a
/-->/!{
N
ba
}
:c
s:<!--.*-->::
s/^.*(kernel)?.*$/$1/g
s/^.*="\(\(kernel\|driver\)[^"]*\).*$/\1/p
s/<base href="\([^"]*\)">/\1/p
')


# Den aktuell installierten Kernel herausfinden (ob kanotix oder kanotix64)
AKTUELLER_KERNEL=$(uname -r)

if uname -r | grep -q -- "-kanotix64-"; then
    AKTUELLER_KERNEL_TYP="kanotix64"
else
    AKTUELLER_KERNEL_TYP="kanotix"
fi

# Die kernel*-Dateien rausfiltern
LIST_KERNEL_FILES=$(echo -e "$LIST_KUPD_FILES" | egrep "^kernel")

# Die driver*-Dateien rausfiltern
LIST_DRIVER_FILES=$(echo -e "$LIST_KUPD_FILES" | egrep "^driver")


if [ -z "$LIST_KERNEL_FILES" ]; then
    dialogMsg $"No kernels were found on the kernel-mirror. Perhaps the server is down or the URL has changed."
    return 1
fi
# Kernel-Auswahl-Dialog erstellen
KERNEL_AUSWAHL_DIALOG="dialogRadioList \""$"Select kernel:""\""
for KERNEL in $LIST_KERNEL_FILES
do
    # Vorauswahl treffen (den Kernel, der den gleichen Typ hat wie der aktuell installierte Kernel)
    PRESEL="off"
    if echo "$KERNEL" | egrep -q "$AKTUELLER_KERNEL_TYP-current"; then
        PRESEL="on"
    fi
    KERNEL_AUSWAHL_DIALOG="$KERNEL_AUSWAHL_DIALOG "$KERNEL" "$KERNEL" "$PRESEL"";
done
# Kernel-Auswahl-Dialog anzeigen
SELECTED_KERNEL_FILE=$(eval "$KERNEL_AUSWAHL_DIALOG")

if [ $? -ne 0 ]; then
    # Abbrechen gedrckt
    return 1
fi

if [ "$LIST_DRIVER_FILES" ]; then
    # Driver-Auswahl-Dialog erstellen
    DRIVER_AUSWAHL_DIALOG="dialogRadioList \""$"Select additional drivers:

(select 'Cancel' if you don't want
to install additional drivers)""\""
    for DRIVER in $LIST_DRIVER_FILES
    do
        # Vorauswahl treffen (den Treiber, der den gleichen Typ hat wie der aktuell installierte Kernel)
        PRESEL="off"
        if ( echo "$DRIVER" | grep -e "-$AKTUELLER_KERNEL_TYP-" >/dev/null); then
            PRESEL="on"
        fi
        DRIVER_AUSWAHL_DIALOG="$DRIVER_AUSWAHL_DIALOG "$DRIVER" "$DRIVER" "$PRESEL"";
    done
    # Driver-Auswahl-Dialog anzeigen
    SELECTED_DRIVER_FILE=$(eval "$DRIVER_AUSWAHL_DIALOG")
    
    if [ $? -ne 0 ]; then
        # Abbrechen gedrckt, also keine zustzlichen Treiber
        SELECTED_DRIVER_FILE=""
    fi
fi

# Base-Directory fr den Download suchen (<base ...>)
DL_BASEDIR=$(echo -e "$LIST_KUPD_FILES" | egrep "^http")
# falls nicht vorhanden einfach den Kernel-Mirror verwenden
[ -z "$DL_BASEDIR" ] && DL_BASEDIR="$KERNEL_MIRROR"

# Die runterzuladenden Dateien bestimmen
DL_FILES_TO_DOWNLOAD="$DL_BASEDIR$SELECTED_KERNEL_FILE"
[ $SELECTED_DRIVER_FILE ] && DL_FILES_TO_DOWNLOAD="$DL_FILES_TO_DOWNLOAD
$DL_BASEDIR$SELECTED_DRIVER_FILE"

fi # <-- noch von der Abfrage manuell oder automatisch

dialogYesNo $"The following files will be downloaded now:""

$DL_FILES_TO_DOWNLOAD

"$"Do you want to continue?"

if [ $? -ne 0 ]; then
    # Abbrechen gedrckt, also doch nichts runterladen
    return 1;
fi

# Download-Ordner bestimmen
KERNELNAME=$(basename "$SELECTED_KERNEL_FILE" ".zip")
DL_DIR="/usr/src/kernelupdate-$KERNELNAME"
mkdir -p "$DL_DIR"
cd "$DL_DIR"

# Jetzt die Dateien runterladen
for DL_FILE in $DL_FILES_TO_DOWNLOAD
do
    DL_PATH="$DL_DIR/$(basename $DL_FILE)"
    if [ ! -e "$DL_PATH" ]; then
        downloadFile "$DL_FILE" "$DL_PATH"
        unzip -o "$(basename $DL_FILE)" -d "$(basename $DL_FILE ".zip")"
    else
        unzip -o "$(basename $DL_FILE)" -d "$(basename $DL_FILE ".zip")"
    fi
done

# Wenn der "current"-Kernel verwendet wurde, dann das Verzeichnis noch umbenennen
if echo "$KERNELNAME" | grep -q current; then
    cd "$KERNELNAME"
    eval "$(egrep "^VER=" install-kernel-kanotix.sh)"
    cd ..
    mv "$KERNELNAME" "kernel-$VER"
    KERNELNAME="kernel-$VER"
    # FIXME: cd "$(dirname "$DL_DIR")"
    cd ..
    mv "$(basename "$DL_DIR")" "kernelupdate-$KERNELNAME"
    cd "kernelupdate-$KERNELNAME"
fi

dialogYesNo $"Do you want to continue the kernel update now?" || return 1

cd "$KERNELNAME"
executeInConsole "./install-kernel-kanotix.sh"
DEBS_IN_KERNEL_PACKAGE=$(ls *.deb | grep -e modules -e ndiswrapper-utils | egrep -v -e '^kernel' | perl -pe 's/((.*?)(-|_.*)(module|kanotix).*)/\2\/\1/g' | grep "/")
DEB_AUSWAHL_DIALOG="dialogCheckList '"$"What packages do you want to install?""'"
IFS="
"
for DEB in $DEBS_IN_KERNEL_PACKAGE
do
    DEB_AUSWAHL_DIALOG="$DEB_AUSWAHL_DIALOG \"${DEB%/*}\" \"\" on"
done
PACKAGES_TO_INSTALL="$(eval "$DEB_AUSWAHL_DIALOG")"
for PACKAGE in $PACKAGES_TO_INSTALL
do
    dpkg -i "$(echo "$DEBS_IN_KERNEL_PACKAGE" | sed -n "s/^$PACKAGE\/\(.*\)$/\1/p")"
done
cd ..

# Wenn zustzliche Treiber installiert werden mssen
if [ "$SELECTED_DRIVER_FILE" ]; then
    DRIVERNAME=$(basename "$SELECTED_DRIVER_FILE" ".zip")
    cd "$DRIVERNAME"
    executeInConsole "dpkg --force-all -i *deb"
fi

# Kano's Scripts updaten
update-scripts-kanotix.sh | dialogWaitBox $"Updating Kano's Scripts..."

dialogYesNo $"The computer has to restart now.

After the reboot some more things have to be done to complete the
update. Kanotix-Update-GUI can do this automagically by starting
itself after the next boot.

If you select 'No' the script exits and you have to do the rest
yourself. Find further instructions in the Kanotix wiki
(http://wiki.kanotix.net/CoMa.php?CoMa=Kanotix-Kernel-UpdateEN)

Do you want to continue automagically? ('No' exits the script)"

[ $? -ne 0 ] && exit 0

# Automatisch fortfahren:
createInitScript "kernelUpdate"

dialogYesNo $"Kanotix-Update-GUI will be started automagically after rebooting.

There you can also install graphics drivers and configure your sound card.
The computer has to be restarted. Save all open files
and close all other running applications.

If you want Kanotix-Update-GUI to restart your computer
select 'Yes', otherwise select 'No'.

Restart the computer now?"

[ $? -ne 0 ] && exit 0

reboot

exit 0
}

# Macht das dist-Upgrade
function distUpgrade()
{
    dialogYesNo $"dist-upgrade

A dist-upgrade works as follows: first a list of packages to be updated 
will be created. Second these files will be downloaded. While downloading
you can use the computer as usual - you will be informed, when the download
finishes. As the actual upgrading process will be executed in runlevel 3
you will have to save all open files and close all running applications at
that point.
After finishing the dist-upgrade the computer will switch back to runlevel 5 and 
you can continue where you left off.

Do you want to do a dist-upgrade as explained above?"
    
    [ $? -ne 0 ] && return 1

    if lsof "/var/lib/dpkg/lock"; then
        dialogMsg $"Lockfile /var/lib/dpkg/lock is in use.\nIs another process using it?"
        return 1
    elif lsof "/var/lib/apt/lists/lock"; then
        dialogMsg $"Lockfile /var/lib/apt/lists/lock is in use.\nIs another process using it?"
        return 1
    fi
    
    # Paketliste aktualisieren und neue Pakete runterladen
    aptUpdate
    
    if LC_ALL=C LANG=C apt-get --simulate dist-upgrade | egrep --quiet "^0 (packages|upgraded)"; then
        # Es sind keine Pakete upzudaten
        dialogMsg $"There are no packages to update!\n\nLooks like we're done ;)"
        return 0
    fi
    
    executeInConsole "apt-get dist-upgrade -d"
    [ $? -ne 0 ] && dialogMsg $"An error occoured while downloading" && return 1
    
    dialogYesNo $"dist-upgrade

All packages to be updated have been downloaded to your computer - so we're ready to start the upgrading process. 
As this will be executed in runlevel 3, you should now save all open files and close all running applications.

Switch to runlevel 3 and start the dist-upgrade?"
    
    [ $? -ne 0 ] && exit 0
    
    createInitScript "distUpgrade"
    chvt 7 || chvt -t 7
    init 3
    /etc/init.d/kdm stop # Bugfix, wenn kdm bei init 3 nicht gestoppt wird (http://forum.kanotix.net/viewtopic.php?p=54322)
    chvt 7 || chvt -t 7
}

function kanoUpdate()
{
    # Kano's Scripte updaten
    if [ ! -e /usr/local/bin/update-scripts-kanotix.sh ]  ; then
        dialogMsg $"The script update-scripts-kanotix.sh is missing!\n\nTherefore the update cannot be continued."
    elif [ "$OFFLINE_MODE" ]; then
        debug "Offline-Modus, no \"update-scripts-kanotix.sh\" possible."
    else
        executeInConsole "update-scripts-kanotix.sh"
    fi
}

function aptUpdate()
{
    # "apt-get update" ausfhren
    [ $OFFLINE_MODE ] && return 1;
    

    if lsof "/var/lib/dpkg/lock"; then
        dialogMsg $"Lockfile /var/lib/dpkg/lock is in use.\nIs another process using it?"
    elif lsof "/var/lib/apt/lists/lock"; then
        dialogMsg $"Lockfile /var/lib/apt/lists/lock is in use.\nIs another process using it?"
    else
        AU_ERROR=$"An error has occoured! Do you want to try apt-get update again? [Y/n]"
        executeInConsole 'while [ "$NOCHMAL" != "n" ]' "do" "apt-get update && break" "echo -e \"\a\n$AU_ERROR\"" "read -n1 NOCHMAL" "done" "NOCHMAL="
    fi
}

function netUpdateMenu()
{
    # Netzwerk-Update Men anzeigen
    while true
    do
        TODO=$(dialogMenu $"Network-Update\nPlease select:" \
"L" $"Readme" \
" " " " \
"S" $"Dist-Upgrade (provide package list as server)" \
"C" $"Dist-Upgrade (use another server's package list as client)" \
" " " " \
"Z" $"Back")
        [ $? -ne 0 ] && break; # Wenn Abbrechen gedrckt, dann beenden
        case "${TODO:0:1}" in
        "Z")
            break;
            ;;
        "L")
            netLiesmich
            ;;
        "S")
            netUpdateServer
            ;;
        "C")
            netUpdateClient
            ;;
        esac
    done
    return 0
}

function netLiesmich()
{
# Liesmich-Text fr Netzwerk-Update anzeigen
dialogMsg $"Network-Update Readme

Running the update in server mode (selection S) will create a list of all deb files
in your apt-cache (/var/cache/apt/) and store it in a file Packages. Additionally your 
apt-cache will be shared by NFS. For details see the respective manpages of exports and nfs. 

Running the update as client (selection C) will ask you for the server's IP number. It 
will mount the server's apt-cache (aka /var/cache/apt/) to /mnt/apt/ by NFS. Your
/etc/apt/sources.list will be backed up and the original file prepended by the entry

deb file:/mnt/apt archives/

Thus the following dist-upgrade will use the NFS connection to the server. Therefore the server
must not be powered down or disconnected, because in this case the missing files will be
retrieved from the internet."
}

function netUpdateServer()
{
    if ( exportfs -v | grep -i "/var/cache/apt" ) && [ -e "/var/cache/apt/archives/Packages" ]; then
        # Zur Zeit luft der Computer als Server
        dialogYesNo $"Network-Update

Kanotix-Update-GUI has detected that this computer is currently sharing its deb
files for other computers to dist-upgrade (i.e.: there is a file Packages
and /var/cache/apt/ is shared by NFS).

Do you want to change this and delete the share?"
        if [ $? -eq 0 ]; then
            sed -e '/#K-U-GUI#/d' /etc/exports > /etc/exports.tmp
            mv -f /etc/exports.tmp /etc/exports
            exportfs -ra
            rm "/var/cache/apt/archives/Packages"
            dialogMsg $"The share has been removed now."
            return 0
        else
            return 1
        fi
    fi

    dialogYesNo $"NOTE: the Network-Update-mode is currently little tested and still experimental.\n\nThere is no guarantee for the thing to work and not to break anything!\n\nDo you want to proceed anyway?"
    [ $? -ne 0 ] && return 1
    
    cd "/var/cache/apt"
    rm "archives/Packages" # alte Packages-Datei lschen

    executeInConsole 'cd "/var/cache/apt"' 'dpkg-scanpackages archives /dev/null > archives/Packages'

    # Portmap starten
    /etc/init.d/portmap start

    # NFS-Server starten
    /etc/init.d/nfs-kernel-server start
    
    # /var/cache/apt exportieren
    if ! ( exportfs -v | grep -i "/var/cache/apt" ); then
        echo "/var/cache/apt/ *(async,all_squash) #K-U-GUI#" >> "/etc/exports"
        exportfs -ra
    fi
    
    # IP-Adressen auflisten
    IP_ADRESSEN=$(ifconfig | grep "inet" | cut -d: -f2 | cut -d" " -f1 | sed -e '/127\.0\.0\.1/d;/^$/d')
    dialogMsg $"Network-Update

The package list has been created and shared. Now start Kanotix-Update-GUI on the other computer (client)
and select network update in client mode (selection C). You will be prompted for this server's IP number,
which is:

$IP_ADRESSEN

!!!! Important !!!!

During the dist-upgrade you MUST NOT power off or 
disconnect this computer (server)!"
}

function netUpdateClient()
{
    # Beim Update als Client (Auswahl C) wird auf dem PC, auf dem das Script gestartet wurde,
    # nach der IP-Adresse des Servers gefragt. Danach wird das Verzeichnis /var/cache/apt per
    # NFS nach /mnt/apt gemountet. Dann wird die /etc/apt/sources.list gebackupt und in der
    # Originaldatei an den Anfang folgender Eintrag hinzugefgt:
    # 
    # deb file:/mnt/apt archives/
    # 
    # Dadurch wird beim anschlieenden Dist-Upgrade die bestehende NFS-Verbindung zum Server
    # genutzt. Whrend des Upgrades sollte der Server deshalb nicht ausgeschaltet oder vom
    # Netzwerk getrennt werden, da sonst versucht wird die fehlenden Dateien vom Internet
    # nachzuladen.
    
    if ( grep "#K-U-GUI#" "/etc/apt/sources.list" ); then
        dialogYesNo $"Network-Update

Kanotix-Update-GUI has detected that this computer is configured to use
packages shared by another computer (i.e. it already is in client mode)

Do you want to change this and delete these settings?"
        if [ $? -eq 0 ]; then
            sed -e '/#K-U-GUI#/d' /etc/apt/sources.list > /etc/apt/sources.list.tmp
            mv -f /etc/apt/sources.list.tmp /etc/apt/sources.list
            ( mount | grep "/mnt/apt" ) && umount -f "/mnt/apt" # NFS-Share umounten wenn es noch gemountet ist
            [ -e "/mnt/apt" ] && rm -rf "/mnt/apt" # Wenn der Mountpoint noch existiert dann lschen
            dialogMsg $"The settings have been deleted."
            return 0
        else
            return 1
        fi
    fi

    dialogYesNo $"NOTE: the Network-Update-mode is currently little tested and still experimental.\n\nThere is no guarantee for the thing to work and not to break anything!\n\nDo you want to proceed anyway?"
    [ $? -ne 0 ] && return 1

    HOST=$(dialogInputBox $"Enter the server's IP number:")
    [ $? -ne 0 ] && return 1 # Abbrechen gedrckt

    # /var/cache/apt auf dem Server nach /mnt/apt mounten
    mkdir -p /mnt/apt
    # Bugfix: wenn der Portmap-Daemon nicht luft dauert das NFS-Mounten ewig, darum hier berprfen
    pidof portmap >/dev/null || /etc/init.d/portmap start
    # NFS mounten
    mount -t nfs $HOST:/var/cache/apt "/mnt/apt"
    if [ $? -ne 0 ]; then
        umount -f "/mnt/apt"
        rm -r "/mnt/apt"
        dialogMsg $"An error occoured while mounting. The network update cannot be continued."
        return 1
    fi
    
    # Die Quelle /mnt/apt/archives als Apt-Get Quelle hinzufgen
    TEMP_FILE_SOURCES=$(createTempFile)
    echo "deb file:/mnt/apt archives/ #K-U-GUI#" > "$TEMP_FILE_SOURCES"
    cat "/etc/apt/sources.list" >> "$TEMP_FILE_SOURCES"
    cat "$TEMP_FILE_SOURCES" > "/etc/apt/sources.list"
    removeTempFile "$TEMP_FILE_SOURCES"
    
    # Fertig gemountet, jetzt kann das Update durchgefhrt werden
    dialogYesNo $"Network-Update

Kanotix-Update-GUI has configured your computer to use the server ($HOST) as package repository.

You can now start the update.

Wnen the update is done and the computer has returned to runlevel 5,
simply start Kanotix-Update-GUI again and choose network update in 
client mode (selection C). You will then be asked if you want to undo
the system configuration changes and return your computer to its 
initial state (i.e. no longer using a server for upgrades).

Do you want to start the dist-upgrade now?"
    [ $? -eq 0 ] && distUpgrade
    return 0
}

# Fgt Apt-Sources der sources.list hinzu
function addAptSources()
{
    dialogYesNo $"Here you can add new apt-sources to your /etc/apt/sources.list.
To this end a list with available sources will be downloaded from the internet.

Do you want to continue?"
    [ $? -ne 0 ] && return 1
    
    SECTIONS_FILE="/tmp/sections.$RANDOM.list"; debug "sections.list: $SECTIONS_FILE"
    if [ "$OFFLINE_MODE" ]; then
        cp "/usr/share/kanotix-update-gui/sections.list" "$SECTIONS_FILE"
    else
        downloadFile "http://www.andreas-loibl.de/linux/sections.list" "$SECTIONS_FILE"
    fi
    
    LIST_OF_SECTIONS=$(cat "$SECTIONS_FILE" | sed -n -e 's/^<Section \(.*\)>$/\1/p')
    debug "$LIST_OF_SECTIONS"
    
    # Gibt den Inhalt der angegebenen Section aus
    function sectionInfo()
    {
        SECTION_ESCAPED="$1"
        SECTION_ESCAPED="${SECTION_ESCAPED//\//\\/}"
        COMMAND="cat \"$SECTIONS_FILE\" | sed -n -e '/<Section $SECTION_ESCAPED>/!bc"
        COMMAND="$COMMAND
:a
N
/<\/Section>/!ba
p
:c
d'
"
        eval "$COMMAND"
        debug "$COMMAND"
    }
    
    # Als Trennzeichen "Newline" verwenden
    IFS="
"
    for SECTION in $LIST_OF_SECTIONS
    do
        SOURCES_OF_SECTION=$(sectionInfo "$SECTION" | egrep ^\s*deb)
        for SOURCE in $SOURCES_OF_SECTION
        do
            SOURCE_EXPR=$(echo "$SOURCE" | sed -e 's/\(http:\/\/.*\)\/ /\1 /g; s/\(http:\/\/[^ ]*\)/\1[\/]?/g')
            if [ "$(egrep "^\s*$SOURCE_EXPR" /etc/apt/sources.list)" ]; then
                INSTALLED_SECTIONS="$INSTALLED_SECTIONS
$SECTION"
                break
            fi
        done
    done
    
    NOT_INSTALLED_SECTIONS="$( ( echo "$INSTALLED_SECTIONS"; echo "$LIST_OF_SECTIONS" ) | sort | uniq -u )"
    echo "$NOT_INSTALLED_SECTIONS"
    SECTION_AUSWAHL_DIALOG="dialogCheckList \""$"The following sections are not yet activated on your computer.

Select the ones you want to add.""\""

    for SECTION in $NOT_INSTALLED_SECTIONS
    do
        SECTION_AUSWAHL_DIALOG="$SECTION_AUSWAHL_DIALOG \"$SECTION\" \"\" off"
    done
    SECTIONS_TO_ADD=$(eval "$SECTION_AUSWAHL_DIALOG")

    [ $? -ne 0 ] && rm "$SECTIONS_FILE" && return 1 # Abbrechen gedrckt

    # "Output" erzeugen (das, was an die /etc/apt/sources.list angehngt wird)
    OUTPUT=""
    for SECTION in $SECTIONS_TO_ADD
    do
        OUTPUT="$OUTPUT
# $SECTION
"
        OUTPUT="${OUTPUT}$(sectionInfo "$SECTION" | sed -e '/^</d' )
"
    done

    dialogYesNo $"The selected sections will be added to your

/etc/apt/sources.list

Do you want to continue?"

    [ $? -ne 0 ] && rm "$SECTIONS_FILE" && return 1

    echo "$OUTPUT" >> /etc/apt/sources.list
    
    rm "$SECTIONS_FILE"
    
    dialogYesNo "The new sections were added and will be available after
an 'apt-get update'.

Do you want to execute 'apt-get update' now?"

    [ $? -ne 0 ]  && return 1
    
    aptUpdate
}

function installSoftware()
{
    dialogYesNo $"Install new software

This feature lets you install those packages already present
in newer kanotix versions. It will retrieve a package list from the internet,
compare it with the packages already installed on your computer and 
allow you to select which of these files to install.

Do you want to continue?"
    [ $? -ne 0 ] && return 1;

    SOFTWARE_FILE="/tmp/software-list-$$"
    if [ "$OFFLINE_MODE" ]; then
        cp "/usr/share/kanotix-update-gui/software.list" "$SOFTWARE_FILE"
    else
        downloadFile "http://www.andreas-loibl.de/linux/software.list" "$SOFTWARE_FILE"
    fi

    LIST_OF_SOFTWARE=$(cat "$SOFTWARE_FILE" | sed -n -e 's/^<Software \(.*\)>$/\1/p')
    debug "$LIST_OF_SOFTWARE"
    
    # Gibt den Inhalt des angegebenen Software-Pakets aus
    function softwareInfo()
    {
        SOFTWARE_ESCAPED="$1"
        SOFTWARE_ESCAPED="${SOFTWARE_ESCAPED//\//\\/}"
        COMMAND="cat \"$SOFTWARE_FILE\" | sed -n -e '/<Software $SOFTWARE_ESCAPED>/!bc"
        COMMAND="$COMMAND
:a
N
/<\/Software>/!ba
p
:c
d'
"
        eval "$COMMAND"
    }
    
    # Als Trennzeichen "Newline" verwenden
    IFS="
"
    SOFTWARE_NOT_INSTALLED_TEMP=$(createTempFile)
    echo "$LIST_OF_SOFTWARE" > "$SOFTWARE_NOT_INSTALLED_TEMP"

    function softwareList()
    {
        SOFTWARE_NOT_INSTALLED="$(cat "$SOFTWARE_NOT_INSTALLED_TEMP")"
        MAX=$(echo "$LIST_OF_SOFTWARE" | wc -l)
        I=0
        for SOFTWARE in $LIST_OF_SOFTWARE
        do
            PACKAGES_OF_SOFTWARE=$(softwareInfo "$SOFTWARE" | sed -n -e 's/^[ ]*\([^<]*\)$/\1/p')

            for PACKAGE in $PACKAGES_OF_SOFTWARE
            do
                # berprfen, ob das Paket schon installiert ist
                if [ "$(dpkg --get-selections $PACKAGE 2>/dev/null)" ]; then
                    SOFTWARE_NOT_INSTALLED="$(echo "$SOFTWARE_NOT_INSTALLED" | sed -e "/^$SOFTWARE\$/d")"
                    debug "$PACKAGE: installiert, also ist \"$SOFTWARE\" bereits installiert"
                    break
                fi
                # Wenn nicht, dann auf die Liste der zu installierenden Pakete setzen
                debug "$PACKAGE: nicht installiert"
            done
            I=$[I+1]
            echo $(expr $I \* 100 / $MAX)
        done
        echo "$SOFTWARE_NOT_INSTALLED" > "$SOFTWARE_NOT_INSTALLED_TEMP"
        echo 101
    }
    
    softwareList | $DIALOG --gauge $"Creating list of packages...\n\nplease wait..." 0 0 0

    SOFTWARE_NOT_INSTALLED="$(cat "$SOFTWARE_NOT_INSTALLED_TEMP")"
    removeTempFile "$SOFTWARE_NOT_INSTALLED_TEMP"

    debug "SOFTWARE_NOT_INSTALLED: $SOFTWARE_NOT_INSTALLED"
    
    if [ -z "$SOFTWARE_NOT_INSTALLED" ]; then
        #Alles ist bereits installiert
        dialogMsg $"All packages are already installed on your computer!"
        return 1
    fi
    
    SOFTWARE_TO_INSTALL="dialogCheckList \""$"The following packages are included in the latest Kanotix release,\nbut missing on your system.\n\nWhich of them do you want to install?""\""
    
    for SOFTWARE in $SOFTWARE_NOT_INSTALLED
    do
        SOFTWARE_INFO=$(softwareInfo "$SOFTWARE")
        SOFTWARE_DESCRIPTION=$(echo "$SOFTWARE_INFO" | sed -n -e 's/^.*<Description>\(.*\)<\/Description>.*$/\1/p')
        SOFTWARE_TO_INSTALL="$SOFTWARE_TO_INSTALL \"$SOFTWARE\" \"$SOFTWARE_DESCRIPTION\" on"
    done

    SOFTWARE_TO_INSTALL=$(eval "$SOFTWARE_TO_INSTALL")
    [ $? -ne 0 ] && return 1
    
    for SOFTWARE in $SOFTWARE_TO_INSTALL
    do
        SOFTWARE_INFO=$(softwareInfo "$SOFTWARE")
        PACKAGES_LIST="$PACKAGES_LIST $( echo $( echo "$SOFTWARE_INFO" | sed -n -e 's/^[ ]*\([^<]*\)$/\1/p' ))"
        if ( echo "$SOFTWARE_INFO" | grep "<Section" ); then
            # Diese Software braucht einen speziellen Eintrag in die sources.list
            SECTION=$(echo "$SOFTWARE_INFO" | sed -n -e 's/^[ ]*<Section \(.*\)>$/\1/p')
            debug "$SECTION"
            APT_SECTIONS_NEEDED="$APT_SECTIONS_NEEDED
$SECTION"
        fi
    done
    
    # Fr die ausgewhlten Softwarepakete werden noch zustzliche Apt-Quellen gebraucht
    if [ "$APT_SECTIONS_NEEDED" ]; then
        for SECTION in $APT_SECTIONS_NEEDED
        do
            # (ich hab ein paar Probleme mit dem Escapen von dem Grep-Befehl....)
            GREP_CMD="${SECTION}"
            GREP_CMD="${GREP_CMD//(/\\(}"
            GREP_CMD="${GREP_CMD//)/\\)}"
            GREP_CMD="${GREP_CMD//+/\\+}"

            GREP_CMD="^[ ]*#[ ]*${GREP_CMD}[ ]*\$"
            GREP_CMD="egrep -i '$GREP_CMD' /etc/apt/sources.list"

            if ! ( eval "$GREP_CMD" ); then
                debug "$SECTION: muss noch installiert werden"
                APT_SECTIONS_TO_ADD="$APT_SECTIONS_TO_ADD
$SECTION"
            fi
        done
    fi
    
    rm "$SOFTWARE_FILE"
    
    # Wenn es Software gibt, die Apt-Quellen braucht, die NICHT in der sources.list stehen
    if [ "$APT_SECTIONS_TO_ADD" ]; then
        dialogYesNo $"To be able to retrieve certain software packages, additional sources have to be added
to your sources list. This can be done with Kanotix-Update-GUI by selecting 'add apt-sources' from 
the main menue. There you can select the missing sections and have them added to your /etc/apt/sources.list

The following sections are missing:

$APT_SECTIONS_TO_ADD

It is, though, also possible, that these sources actually are in your sources list,
but didn't get recognized (there has to be a comment line stating the section name right before 
the source line). So if you are sure that the source is already listed (e.g. because it doesn't
show up in 'Add APT-Sources') you can still proceed by selecting 'No'.

Do you want to cancel now?"
        [ $? -ne 1 ] && return 1
    fi
    
    aptUpdate
    REUNFREEZE=
    [ ! -e "/etc/frozen-rc.d" ] && REUNFREEZE=1 && freeze-rc.d
    executeInConsole "apt-get install $PACKAGES_LIST"
    [ $REUNFREEZE ] && unfreeze-rc.d
}

# Kanotix-Update-GUI updaten
function kuguiUpdate()
{
    [ "$OFFLINE_MODE" ] && return 1
    executeInConsole "apt-get update" "apt-get install kanotix-update-gui" "read -t2"
    kanotix-update-gui
    exit 0
}

# Upgrade-Warnungen auflisten
function upgradeWarnings()
{
    [ "$OFFLINE_MODE" ] || dialogYesNo $"Upgrade-News/Warnings

Upgrade-News/Warnings can be fetched from the internet. You should read them before any upgrade
and use the tips given there or wait with the Upgrade until there is a better time for upgrading.

Source: http://www.andreas-loibl.de/linux/upgrade-news.en

Do you want to fetch the Upgrade-News/Warnings from the internet?"

    [ $? -ne 0 ] && return 1
    
    WARNINGS_FILE="$(createTempFile)"
    
    if [ "$LANGUAGE" = "de" ]; then
        FILE="upgrade-news.de"
    else
        FILE="upgrade-news.en"
    fi
    
    if [ "$OFFLINE_MODE" ]; then
        dialogTextBox "/usr/share/kanotix-update-gui/$FILE"
    else
        downloadFile "http://www.andreas-loibl.de/linux/$FILE" "$WARNINGS_FILE"
        dialogTextBox "$WARNINGS_FILE"
    fi
    
    removeTempFile "$WARNINGS_FILE"
}

# Offline-Upgrade
function offlineUpdate()
{
        offlineUpdate_stage0
}

function offlineUpdate_stage0()
{
    # Trennzeichen: Newline
    IFS="
"

    # NOTE: Upgrade-Warnungen:
    # "1" "Upgrade-News/Warnings" on
    THINGS_TO_UPDATE=$(dialogCheckList $"What do you want to upgrade?" "2" $"Package lists" on "3" $"Kernel-Update" off "4" $"Kanotix-Update-GUI" off)
    [ $? -ne 0 ] && return 1
    
    TEMP_FILE="$(createTempFile)"
    echo "# Kanotix-Update-GUI: Offline-Update-File (stage1)" > $TEMP_FILE
    echo "OFFLINE_UPGRADE_STAGE=1" >> "$TEMP_FILE"
    echo "OFFLINE_UPGRADE_ID=\"$(uname -a | md5sum | cut -d " " -f1)\"" >> "$TEMP_FILE"
    
    for THING in $THINGS_TO_UPDATE
    do
        case "$THING" in
        "1")
            echo "OFFLINE_UPGRADE_NEWS=1" >> "$TEMP_FILE"
            ;;
        "2")
            echo "OFFLINE_UPGRADE_SOURCES=\"" >> "$TEMP_FILE"
            apt-get -qq --print-uris update >> "$TEMP_FILE"
            echo "\"" >> "$TEMP_FILE"
            ;;
        "3")
            echo "OFFLINE_UPGRADE_KERNEL_FROM=\"$(uname -r)\"" >> "$TEMP_FILE"
            ;;
        esac
    done

    FILENAME=""
    while [ -z "$FILENAME" ]
    do
        FILENAME="$($DIALOG --fselect "offline_update.stage1.kugui" 0 0)"
        [ $? -ne 0 ] && removeTempFile "$TEMP_FILE" && return 1
    done
    
    cp "$TEMP_FILE" "$FILENAME"
    removeTempFile "$TEMP_FILE"
    
    dialogMsg $"The Upgrade-Package has been created (Stage 1).\nPut this file onto the Computer connected to the internet and open it there.\nKanotix-Upgrade-GUI will do the downloads automatically and drop a second \nUpgrade-Package (Stage 2). This file has to be copied back to *this* computer.\nOpen it and the Upgrade will be done (automatically)."
}

function downloadListFile()
{
    URL="$1"
    URL_unp="$(dirname "$URL")/$(basename "$URL" ".bz2")"
    URL_gz="$URL_unp.gz"

    downloadFile "$URL" "$2" || downloadFile "$URL_gz" "$2" || downloadFile "$URL_unp" "$2"
    TEMP_FILE=$(createTempFile)
    case "$(file "$2")" in
    *"gzip compressed data"*)
        gzip -d < "$2" > "$TEMP_FILE"
        ;;
    *"bzip2 compressed data"*)
        bzip2 -d < "$2" > "$TEMP_FILE"
        ;;
    *)
        cp "$2" "$TEMP_FILE"
        ;;
    esac
    mv "$TEMP_FILE" "$2"
}

function offlineUpdate_stage1()
{
    BACK_DIR="$(pwd)"
    TEMP_DIR="/tmp/kugui-offline_update-$$.$RANDOM"
    mkdir -p "$TEMP_DIR"
    cd "$TEMP_DIR"
    
    if [ "$OFFLINE_UPGRADE_NEWS" ]; then
        downloadFile "http://www.andreas-loibl.de/linux/upgrade-news.de" "upgrade-news.de"
        downloadFile "http://www.andreas-loibl.de/linux/upgrade-news.en" "upgrade-news.en"
    fi
    
    if [ "$OFFLINE_UPGRADE_SOURCES" ]; then
        mkdir -p "sources"
        cd "sources"
        CMD=$(echo -n "$OFFLINE_UPGRADE_SOURCES" | awk '{print "downloadListFile " $1 " \"" $2 "\""}')
        eval "$CMD"
        tar cf "sources.tar" .
        cd ..
        mv "sources/sources.tar" "sources.tar"
        rm -r "sources"
    fi
    
    if [ "$OFFLINE_UPGRADE_KERNEL_FROM" ]; then
        # TODO: Download von Grafiktreiber (optional)

        # Erstmal die Seite runterladen, dann die Kommentare entfernen und nach (href)="driver..." und (href)="kernel..." suchen
        LIST_KUPD_FILES=$(wget -q -O - "$KERNEL_MIRROR" | sed -n -e '
        /<!--/!bc
        :a
        /-->/!{
        N
        ba
        }
        :c
        s:<!--.*-->::
        s/^.*(kernel)?.*$/$1/g
        s/^.*="\(\(kernel\|driver\)[^"]*\).*$/\1/p
        s/<base href="\([^"]*\)">/\1/p
        ')
        
        
        # Den aktuell installierten Kernel herausfinden (ob kanotix oder kanotix64)
        AKTUELLER_KERNEL=$OFFLINE_UPGRADE_KERNEL_FROM
        if echo -n "$OFFLINE_UPGRADE_KERNEL_FROM" | grep -q -- "-kanotix64-"; then
            AKTUELLER_KERNEL_TYP="kanotix64"
        else
            AKTUELLER_KERNEL_TYP="kanotix"
        fi
        
        # Die kernel*-Dateien rausfiltern
        LIST_KERNEL_FILES=$(echo -e "$LIST_KUPD_FILES" | egrep "^kernel")
        
        # Die driver*-Dateien rausfiltern
        LIST_DRIVER_FILES=$(echo -e "$LIST_KUPD_FILES" | egrep "^driver")
        
        # Kernel-Auswahl-Dialog erstellen
        # TODO: Locale
        KERNEL_AUSWAHL_DIALOG="dialogRadioList \""$"Select kernel:""\""
        for KERNEL in $LIST_KERNEL_FILES
        do
            # Vorauswahl treffen (den Kernel, der den gleichen Typ hat wie der aktuell installierte Kernel)
            PRESEL="off"
            if echo "$KERNEL" | egrep -q "$AKTUELLER_KERNEL_TYP-current"; then
                PRESEL="on"
            fi
            KERNEL_AUSWAHL_DIALOG="$KERNEL_AUSWAHL_DIALOG "$KERNEL" "$KERNEL" "$PRESEL"";
        done
        # Kernel-Auswahl-Dialog anzeigen
        SELECTED_KERNEL_FILE=$(eval "$KERNEL_AUSWAHL_DIALOG")
        
        if [ $? -ne 0 ]; then
            # Abbrechen gedrckt
            return 1
        fi
        
        if [ "$LIST_DRIVER_FILES" ]; then
            # Driver-Auswahl-Dialog erstellen
            DRIVER_AUSWAHL_DIALOG="dialogRadioList \""$"Select additional drivers:

(select 'Cancel' if you don't want
to install additional drivers)""\""
            for DRIVER in $LIST_DRIVER_FILES
            do
                # Vorauswahl treffen (den Treiber, der den gleichen Typ hat wie der aktuell installierte Kernel)
                PRESEL="off"
                if ( echo "$DRIVER" | grep -e "-$AKTUELLER_KERNEL_TYP-" >/dev/null); then
                    PRESEL="on"
                fi
                DRIVER_AUSWAHL_DIALOG="$DRIVER_AUSWAHL_DIALOG "$DRIVER" "$DRIVER" "$PRESEL"";
            done
            # Driver-Auswahl-Dialog anzeigen
            SELECTED_DRIVER_FILE=$(eval "$DRIVER_AUSWAHL_DIALOG")
            
            if [ $? -ne 0 ]; then
                # Abbrechen gedrckt, also keine zustzlichen Treiber
                SELECTED_DRIVER_FILE=""
            fi
        fi

        # Base-Directory fr den Download suchen
        DL_BASEDIR=$(echo -e "$LIST_KUPD_FILES" | egrep "^http")
        # falls nicht vorhanden einfach den Kernel-Mirror verwenden
        [ -z "$DL_BASEDIR" ] && DL_BASEDIR="$KERNEL_MIRROR"
        
        # Die runterzuladenden Dateien bestimmen
        DL_FILES_TO_DOWNLOAD="$DL_BASEDIR$SELECTED_KERNEL_FILE"
        [ $SELECTED_DRIVER_FILE ] && DL_FILES_TO_DOWNLOAD="$DL_FILES_TO_DOWNLOAD
        $DL_BASEDIR$SELECTED_DRIVER_FILE"
        
        # Download-Ordner bestimmen
        KERNELNAME=$(basename "$SELECTED_KERNEL_FILE" ".zip")
        DL_DIR="$TEMP_DIR/kernel"
        mkdir -p "$DL_DIR"
        cd "$DL_DIR"
        
        # Jetzt die Dateien runterladen
        for DL_FILE in $DL_FILES_TO_DOWNLOAD
        do
            DL_PATH="$DL_DIR/$(basename $DL_FILE)"
            if [ ! -e "$DL_PATH" ]; then
                downloadFile "$DL_FILE" "$DL_PATH"
            fi
        done
        
        # Den runtergeladenen Ordner verpacken und verlassen
        tar cf "kernel.tar" .
        cd ..
        mv "kernel/kernel.tar" "kernel.tar"
        rm -r "kernel"
    fi
    
    echo "# Kanotix-Update-GUI: Offline-Update-File (stage2)
OFFLINE_UPGRADE_ID="$OFFLINE_UPGRADE_ID"
OFFLINE_UPGRADE_STAGE=2

" > "config.sh"

    cd "$BACK_DIR"
    FILENAME=""
    while [ -z "$FILENAME" ]
    do
        FILENAME="$($DIALOG --fselect "offline_update.stage2.kugui" 0 0)"
        [ $? -eq 0 ] || break;
    done
    cd "$TEMP_DIR"
    
    tar czf "$FILENAME" .
    rm -rf "$TEMP_DIR"
}

function offlineUpdate_stage2()
{
    [ -e "update-news.de" ] && cp "update-news.de" "/usr/share/kanotix-update-gui/"
    [ -e "update-news.en" ] && cp "update-news.en" "/usr/share/kanotix-update-gui/"
    if [ -e "sources.tar" ]; then
        tar xvf "sources.tar" -C "/var/lib/apt/lists"
    fi
    # TODO: Grafiktreiber abspeichern
    if [ -e "kernel.tar" ]; then
        mkdir -p "/usr/share/kanotix-update-gui/kernelupdate/"
        tar xvf "kernel.tar" -C "/usr/share/kanotix-update-gui/kernelupdate/"
        KERNELNAME="$(basename "$(ls "/usr/share/kanotix-update-gui/kernelupdate/" | egrep "kernel.*\.zip")" ".zip")"
        DRIVERNAME="$(basename "$(ls "/usr/share/kanotix-update-gui/kernelupdate/" | egrep "driver.*\.zip")" ".zip")"
        mv "/usr/share/kanotix-update-gui/kernelupdate" "/usr/share/kanotix-update-gui/kernelupdate-$KERNELNAME"
        cd "/usr/share/kanotix-update-gui/kernelupdate-$KERNELNAME"

        for ZIP_FILE in *.zip
        do
            unzip -o "$(basename $ZIP_FILE)" -d "$(basename $ZIP_FILE ".zip")"
        done
        
        cd "$KERNELNAME"
        executeInConsole "./install-kernel-kanotix.sh"
        DEBS_IN_KERNEL_PACKAGE=$(ls *.deb | grep -e modules -e ndiswrapper-utils | egrep -v -e '^kernel' | perl -pe 's/((.*?)(-|_.*)(module|kanotix).*)/\2\/\1/g' | grep "/")
        DEB_AUSWAHL_DIALOG="dialogCheckList '$KU_DLG_PACKAGES'"
        IFS="
"
        for DEB in $DEBS_IN_KERNEL_PACKAGE
        do
            DEB_AUSWAHL_DIALOG="$DEB_AUSWAHL_DIALOG \"${DEB%/*}\" \"\" on"
        done
        PACKAGES_TO_INSTALL="$(eval "$DEB_AUSWAHL_DIALOG")"
        for PACKAGE in $PACKAGES_TO_INSTALL
        do
            dpkg -i "$(echo "$DEBS_IN_KERNEL_PACKAGE" | sed -n "s/^$PACKAGE\/\(.*\)$/\1/p")"
        done
        cd ..
        
        # Wenn zustzliche Treiber installiert werden mssen
        if [ "$DRIVERNAME" ]; then
            cd "$DRIVERNAME"
            executeInConsole "dpkg --force-all -i *deb"
        fi
        
        # Kano's Scripts updaten
        update-scripts-kanotix.sh | dialogWaitBox "Updating Kano's Scripts..."
        
        dialogYesNo $"The computer has to restart now.

After the reboot some more things have to be done to complete the
update. Kanotix-Update-GUI can do this automagically by starting
itself after the next boot.

If you select 'No' the script exits and you have to do the rest
yourself. Find further instructions in the Kanotix wiki
(http://wiki.kanotix.net/CoMa.php?CoMa=Kanotix-Kernel-UpdateEN)

Do you want to continue automagically? ('No' exits the script)"
        
        [ $? -ne 0 ] && return 0
        
        # Automatisch fortfahren:
        createInitScript "kernelUpdate"
        
        dialogYesNo $"Kanotix-Update-GUI will be started automagically after rebooting.

There you can also install graphics drivers and configure your sound card.
The computer has to be restarted. Save all open files
and close all other running applications.

If you want Kanotix-Update-GUI to restart your computer
select 'Yes', otherwise select 'No'.

Restart the computer now?"
        
        [ $? -ne 0 ] && return 0
        
        reboot
        
        exit 0

        cd "$TEMP_DIR"
    fi
}

# Parameter auswerten
while [ "$1" ]
do
    case "$1" in
    "nodownload"|"--nodownload")
        ;;
    *)
        if [ -f "$1" ]; then
            case "$(file "$1")" in
            *"ASCII text"*)
                if [ "$(head -n1 "$1")" = "# Kanotix-Update-GUI: Offline-Update-File (stage1)" ]
                then
                    . "$1" # Datei einbinden
                    cd "$(dirname "$1")"
                    offlineUpdate_stage1
                    dialogYesNo $"Kanotix-Update-GUI has done all the downloads successfully and dropped a second \nUpgrade-Package (Stage 2). This file has to be copied back to the computer from which the Stage-1 file was from.\nOpen it there and the Upgrade will be done (automatically).\n\nDo you want to start Kanotix-Update-GUI on this computer now?"
                    [ $? -ne 0 ] && exit 0
                fi
                ;;
            *"gzip compressed data"*)
                TEMP_DIR="/tmp/kugui-offline_update-$$.$RANDOM"
                mkdir -p "$TEMP_DIR"
                tar xzvf "$1" -C "$TEMP_DIR" | dialogWaitBox $"Extracting Contents of Offline-Upgrade-Package..."
                cd "$TEMP_DIR"

                # Prfen, ob das Package von diesem Computer stammt (ansonsten warnen.)
                if [ -e "config.sh" ]; then
                    . "config.sh"
                    debug "$OFFLINE_UPGRADE_STAGE - $OFFLINE_UPGRADE_ID"
                    if [ $OFFLINE_UPGRADE_STAGE -ne 2 ]; then
                        dialogYesNo $"There is something wrong with the Package...""\n"$"It doesn't say that we are at Stage-2.\n\nContinue?"
                        if [ $? -ne 0 ]; then
                            cd /
                            rm -rf "$TEMP_DIR"
                            exit 1
                        fi
                    fi
                    if [ "$OFFLINE_UPGRADE_ID" != "$(uname -a | md5sum | cut -d " " -f1)" ]; then
                        dialogYesNo $"There is something wrong with the Package...""\n"$"The Stage-1-File was from another computer.\n\nContinue?"
                        if [ $? -ne 0 ]; then
                            cd /
                            rm -rf "$TEMP_DIR"
                            exit 1
                        fi
                    fi
                    offlineUpdate_stage2 | dialogWaitBox $"Updating..."
                    cd /
                    rm -rf "$TEMP_DIR"
                    dialogYesNo $"The upgrade finished successfully. Do you want to start Kanotix-Update-GUI now?"
                    [ $? -ne 0 ] && exit 0
                else
                    dialogMsg $"This Package is not a valid Kanotix-Update-GUI-Offline-Upgrade-Package!"
                    cd /
                    rm -rf "$TEMP_DIR"
                    exit 0;
                fi
                ;;
            esac
        fi
        ;;
    esac
    shift
done

# Hauptmen
# NOTE: Update-Warnungen:
# "W" "$MENU_MAIN_ITEM_WARNINGS" \
while true
do
    if [ "$OFFLINE_MODE" ]; then
        TODO=$(dialogMenu "Kanotix-Update-GUI
(Offline-Mode)

"$"Main menu:" \
"I" $"Info" \
"H" $"Help" \
" " " " \
"O" $"Offline-Update" \
" " " " \
"E" $"Exit")
    else
        TODO=$(dialogMenu "Kanotix-Update-GUI
by A.Loibl

"$"Main menu:" \
"I" $"Info" \
"H" $"Help" \
"O" $"Offline-Update" \
" " " " \
"1" $"Kernel-Update" \
"2" $"Dist-Upgrade" \
"3" $"Network-Update" \
"4" $"Update Kano's scripts" \
" " " " \
"5" $"APT-Get Update" \
"6" $"Add APT-Sources" \
"7" $"Install new software" \
"8" $"Update Kanotix-Update-GUI" \
" " " " \
"E" $"Exit")
    fi

    if [ $? -ne 0 ]; then
        break; # Wenn Abbrechen gedrckt, dann beenden
    fi

    debug "Men Auswahl: $TODO"

    case "${TODO:0:1}" in
    "E")
        break # Ende ausgewhlt
        ;;
    "I")
        infoDialog
        ;;
    "H")
        helpDialog
        ;;
    "W")
        upgradeWarnings
        ;;
    "O")
        offlineUpdate
        ;;
    "1")
        kernelUpdate
        ;;
    "2")
        distUpgrade
        ;;
    "3")
        netUpdateMenu
        ;;
    "4")
        kanoUpdate
        ;;
    "5")
        aptUpdate
        ;;
    "6")
        addAptSources
        ;;
    "7")
        installSoftware
        ;;
    "8")
        kuguiUpdate
        ;;
    esac
done

exit 0
