#!/bin/bash
# saveconfig - create KNOPPIX configuration floppy
# (C) Klaus Knopper Mar 2002
# Spanish translation by Luis Llorente, luis.llorente@hispalinux.es

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

XDIALOG_HIGH_DIALOG_COMPAT=1
export XDIALOG_HIGH_DIALOG_COMPAT

# Get root
[ "`id -u`" != "0" ] && exec sudo "$0" "$@"

TMP="/tmp/saveconfig.tmp$$"

bailout(){
rm -f "$TMP" "$TMP.done" "$TMP.err"
umount "$DIRECTORY"
exit 0
}

DIALOG="dialog"
[ -n "$DISPLAY" ] && [ -x /usr/bin/Xdialog ] && DIALOG="Xdialog"

trap bailout 1 2 3 15

# LANGUAGE etc.
[ -f /etc/sysconfig/knoppix ] && . /etc/sysconfig/knoppix
[ -z "$LANG" ] && export LANG
[ -z "$LANGUAGE" ] && export LANGUAGE
[ -z "$CHARSET" ] && export CHARSET

DESKTOPKB="$(du -sk $HOME/Desktop 2>/dev/null | awk '{print $1}')"

# Language-dependent Messages
case "$LANGUAGE" in
de*|at*|ch*)
TITLE1="KNOPPIX Konfigurationsarchiv anlegen"
MESSAGE1="Konfigurationsdateien ausw?len:"
MESSAGE2="Bitte legen Sie jetzt eine leere DOS- oder ext2-formatierte, schreibbare Diskette ein."
MESSAGE3="Archiviere ge?derte Konfigurationsdateien..."
MESSAGE4="Bitte w?len Sie das Verzeichnis, in das Sie die Konfigurationsdateien schreiben wollen."
E1="Pers?liche Einstellungen (Desktop, Programme)"
E2="Netzwerk Einstellungen (LAN, Modem, ISDN, ASDL)"
E3="Grafik Subsystem Einstellungen (XF86Config)"
E4="Weitere systemweite Einstellungen (Drucker etc.)"
E5="Alle Desktop-Dateien (${DESKTOPKB}kB)"
ERROR="Leider konnte die KNOPPIX-Konfiguration NICHT gespeichert werden:"
;;
es*)
TITLE1="Crear un archive de configuraci? de KNOPPIX"
MESSAGE1="Elija el tipo de archivos de configuraci?:"
MESSAGE2="Por favor, inserte un disquete vac? escribible formateado para DOS o ext2."
MESSAGE3="Grabando archivos de la configuraci?..."
MESSAGE4="Por favor, seleccione el directorio para los archivos de la configuraci? del ahorro."
E1="Configuraci? personal (escritorio, programas)"
E2="Configuraci? de Red (LAN, Modem, RDSI, ADSL)"
E3="Configuraci? del subsistema gr?ico (XF86Config)"
E4="Otras configuraciones del sistema (impresora, etc.)"
E5="Todos los archivos en el Escritorio (${DESKTOPKB}kB)"
ERROR="No se pudo crear de configuraci? de KNOPPIX:"
;;
*)
TITLE1="Create KNOPPIX configuration archive"
MESSAGE1="Chose type of configuration files:"
MESSAGE2="Please insert an empty DOS- or ext2-formatted, writable floppy disk."
MESSAGE3="Saving configuration archive..."
MESSAGE4="Please select directory for saving configuration files:"
E1="Personal configuration (desktop, programs)"
E2="Network settings (LAN, Modem, ISDN, ADSL)"
E3="Graphics subsystem settings (XF86Config)"
E4="Other system configuration (printer etc.)"
E5="All files on the Desktop (${DESKTOPKB}kB)"
ERROR="The KNOPPIX configuration could NOT be saved:"
;;
esac

$DIALOG --clear --title "$TITLE1" --checklist "$MESSAGE1" 18 75 9 p "$E1" on d "$E5" off n "$E2" on x "$E3" on o "$E4" on 2>"$TMP" || bailout

FILES=""
SAVEHOME=""
SAVEDESK=""
SAVEETC=""
SAVENET=""
SAVEX=""
CHOWNHOME=""
NETFILES='/etc/network|/etc/ppp|/etc/chat|/etc/isdn|/etc/sysconfig/isdn|/etc/sysconfig/provider|/etc/resolv\.conf|/etc/hosts|/etc/hosts\.|/etc/inetd\.conf'
XFILES='/etc/X11'
for i in `sed 's,",,g;s,/, ,g;' < "$TMP"`; do
case $i in
p) SAVEHOME="yes" ;;
d) SAVEDESK="yes" ;;
n|x|o) SAVEETC="yes"; case "$i" in n) SAVENET="yes";; x) SAVEX="yes";; esac ;;
esac
done

[ -n "$SAVEHOME" -o -n "$SAVEDESK" ] && CHOWNHOME="chown -R $(ls -ld $HOME | awk '{print $3"."$4}') $HOME"

# Find changes in (real) files of dir1 ... dir2
findchanged(){
if [ -d "$1" ]; then
for i in `( cd "$1"; find . -type f | sed 's,^\./,,g' | grep -v ' ' )`; do
cmp -s "$1/$i" "$2/$i" || echo "$1/$i"
done
elif [ -e "$1" ]; then
cmp -s "$1" "$2" || echo "$1"
fi
}

writescript(){
cat >"$1" <<EOT
#!/bin/sh
[ "\`id -u\`" = "0" ] || { echo "You need root privileges to modify the system!" >&2 ; exit 1; }
[ -d "\$1" ] && CONFIGS="\$1/configs.tbz"
[ -f "\$CONFIGS" ] || CONFIGS="/cdrom/KNOPPIX/configs.tbz"
[ -f "\$CONFIGS" ] || CONFIGS="/mnt/floppy/configs.tbz"
if [ -f "\$CONFIGS" ]; then
echo "[1mExtracting config archive \$CONFIGS...[0m"
tar -jpPtf "\$CONFIGS" | while read i; do rm -f "\$i"; done
tar -jpPxf "\$CONFIGS" ; $CHOWNHOME
fi
EOT
return "$?"
}

FLOPPYDIR="$(ls -l /mnt/floppy | awk '{print $NF}')"

umountfloppy(){
mount | grep -q "$FLOPPYDIR" && umount "$FLOPPYDIR" 2>/dev/null
}

# Directory selector
PARTITIONS="/mnt/floppy [Floppy] on"
for i in `awk '/^\/dev\/[hs]d[a-z].*\/mnt\/[hs]d[a-z]/{if(!/ntfs/){print $2}}' /etc/fstab`; do
PARTITIONS="$PARTITIONS ${i} [Disk/Partition] off"
done


rm -f "$TMP"
$DIALOG --clear --title "$TITLE1" --radiolist "$MESSAGE4" 18 75 9 $PARTITIONS 2>"$TMP" || bailout

DIRECTORY="$(<$TMP)"
[ -z "$DIRECTORY" -o ! -e "$DIRECTORY" ] && bailout

case "$DIRECTORY" in *floppy*)
DIRECTORY="$FLOPPYDIR"
KNOPPIXSH="$DIRECTORY/knoppix.sh"
while :; do
umountfloppy
$DIALOG --title "$TITLE1" --yesno "$MESSAGE2" 8 65 || bailout
echo "$FLOPPYDIR" | grep -q auto || mount /mnt/floppy
[ "$?" = "0" ] && writescript "$KNOPPIXSH" && break
done
;;
*)
rm -f "$TMP.err"
mount | grep -q "$DIRECTORY" || mount -r "$DIRECTORY" >"$TMP.err"
[ "$?" != "0" ] && { $DIALOG --title "$TITLE1" --msgbox "$ERROR `cat $TMP.err`" 10 75; bailout; }
mount | grep -q "$DIRECTORY.*ntfs" && { $DIALOG --title "$TITLE1" --msgbox "$ERROR NTFS" 10 75; bailout; }
mount -o remount,rw "$DIRECTORY"
KNOPPIXSH="$DIRECTORY/knoppix.sh"
writescript "$KNOPPIXSH"
esac

gpid=""

gauge(){
status=0
while [ ! -e "$TMP.done" ]; do echo "$status" ; status="`expr \( 100 - $status \) / 4 + $status`"; sleep 2; done | $DIALOG --title "$TITLE1" --gauge "$MESSAGE3" 8 65 0
}

# Start status bar
# if [ "$DIALOG" = "dialog" ]; then
gauge &
# else
## Gauge doesn't work yet with gdialog
# $DIALOG --title "$TITLE1" --gauge "$MESSAGE3" 8 65 75 &
# gpid="$!"
# fi

rm -f "$TMP"
touch "$TMP"

[ -n "$SAVEHOME" ] && for i in $HOME/.??* $HOME/office $HOME/evolution; do findchanged "$i" /etc/skel/$(basename "$i"); done | egrep -v -e '(\.ICEauthority|ksycoka|\.xsession-errors|\.DCOP|\.MCOP|kio_http/cache|\.mozilla/.*/Cache/|favicons|office/user/work)' >"$TMP"
# K.Wonderboy ; 1.11 s
if [ -d $HOME/.openoffice ]; then
   [ -n "$SAVEHOME" ] && for i in $HOME/.openoffice; do echo "$i"; done >>"$TMP"
fi 
if [ -d $HOME/OpenOffice* ] ; then
   [ -n "$SAVEHOME" ] && for i in $HOME/OpenOffice*; do echo "$i"; done >>"$TMP"
fi
# K.Wonderboy ; 1.11 e
[ -n "$SAVEDESK" ] && for i in $HOME/Desktop; do findchanged "$i" /etc/skel/$(basename "$i"); done >>"$TMP"

IGNORE='/etc/ioctl.save|/etc/mtab'

if [ -n "$SAVEETC" -a -d /KNOPPIX/etc ]; then
findchanged /etc /KNOPPIX/etc >>"$TMP"
[ -n "$SAVENET" ] || IGNORE="$IGNORE|$NETFILES"
[ -n "$SAVEX" ] || IGNORE="$IGNORE|$XFILES"
fi

rm -f "$TMP.tmp"
egrep -v -e '('"$IGNORE"')' "$TMP" > "$TMP.tmp"
mv -f "$TMP.tmp" "$TMP"

SCRIPTS=""
STARTNET=""
STARTPCMCIA=""
STARTCUPS=""
REINIT=""

while read i; do
case "$i" in
/etc/network/interfaces) STARTNET="yes";;
/etc/pcmcia/*) STARTPCMCIA="yes";;
/etc/cups*) STARTCUPS="yes";;
/etc/inittab) REINIT="yes";;
esac
done <"$TMP"


[ -n "$STARTNET" ]    && { echo "killall pump 2>/dev/null && sleep 2 && killall -9 pump 2>/dev/null && sleep 2" >>"$KNOPPIXSH" ; SCRIPTS="$SCRIPTS ifupdown networking"; }
[ -n "$STARTPCMCIA" ] && echo 'echo "[1m(Re)starting PCMCIA services.[0m"; killall cardmgr 2>/dev/null && sleep 4; cardmgr && sleep 4' >>"$KNOPPIXSH"
[ -n "$STARTCUPS" ]   && SCRIPTS="$SCRIPTS cupsys"

if [ -n "$SCRIPTS" ]; then
echo 'echo "[1mStarting daemons...[0m"' >>"$KNOPPIXSH"
echo "for i in $SCRIPTS; do [ -x /etc/init.d/\$i ] && /etc/init.d/\$i start; done" >>"$KNOPPIXSH"
fi

[ -n "$REINIT" ] && echo 'echo "[1mReloading INIT.[0m" ; init q' >> "$KNOPPIXSH"

rm -f "$TMP.err"
BZIP2=-9 tar -T - -cpPjf "$DIRECTORY/configs.tbz" <"$TMP" 2>"$TMP.err"

RC="$?"

if [ "$DIRECTORY" = "$FLOPPYDIR" ]; then
umountfloppy
else
umount "$DIRECTORY"
fi

# More language-dependent Messages
case "$LANGUAGE" in
de*|at*|ch*)
SUCCESS="Die KNOPPIX-Konfiguration wurde erfolgreich gespeichert. Ihre Konfigurationsdateien werden beim n?hsten KNOPPIX-Bootvorgang in die Ramdisk restauriert, wenn Sie im Bootscreen \"knoppix myconfig=$DIRECTORY\" bzw. \"knoppix myconfig=scan\" (automatische Suche) angeben."
;;
es*)
SUCCESS="La creaci? del configuraci? de KNOPPIX fue satisfactoria. Sus archivos de configuraci? ser? reinstalados en el siguiente arranque de KNOPPIX si especifica \"knoppix myconfig=$DIRECTORY\" o \"knoppix myconfig=scan\" (automatic) en la l?ea de comandos del arranque."
;;
*)
SUCCESS="Creation of the KNOPPIX configuration archive was successful. Your configuration files will be reinstalled to the ramdisk on next KNOPPIX boot if you specify \"knoppix myconfig=$DIRECTORY\", or \"knoppix myconfig=scan\" (automatic search) at the boot prompt."
;;
esac


# Stop status bar
# [ "$DIALOG" = "dialog" ] && { touch "$TMP.done" ; wait ; rm -f "$TMP.done" ; } || { [ -n "$gpid" ] && kill "$gpid" 2>/dev/null; sleep 1; }
touch "$TMP.done" ; wait ; rm -f "$TMP.done"

[ "$RC" = "0" ] && $DIALOG --title "$TITLE1" --msgbox "$SUCCESS" 12 65 || $DIALOG --title "$TITLE1" --msgbox "$ERROR `cat $TMP.err`" 10 75

bailout
