#!/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/Downloads 2>/dev/null | awk '{print $1}')"

# Language-dependent Messages
case "$LANGUAGE" in
de*|at*|ch*)
TITLE1="KNOPPIX Konfigurationsarchiv anlegen"
MESSAGE1="Konfigurationsdateien auswhlen:"
MESSAGE2="Bitte legen Sie jetzt eine leere DOS- oder ext2-formatierte, schreibbare Diskette ein."
MESSAGE3="Archiviere genderte Konfigurationsdateien..."
MESSAGE4="Bitte whlen Sie das Verzeichnis, in das Sie die Konfigurationsdateien schreiben wollen."
E1="Persnliche Einstellungen (Desktop, Programme)"
E2="Netzwerk und Celliax Einstellungen"
E3="Grafik Subsystem Einstellungen (XF86Config)"
E4="Weitere systemweite Einstellungen (Drucker etc.)"
E5="Alle Downloads-Dateien (${DESKTOPKB}kB)"
ERROR="Leider konnte die KNOPPIX-Konfiguration NICHT gespeichert werden. CDrom auswhlen?"
;;
es*)
TITLE1="Crear un archive de configuracin de KNOPPIX"
MESSAGE1="Elija el tipo de archivos de configuracin:"
MESSAGE2="Por favor, inserte un disquete vaco escribible formateado para DOS o ext2."
MESSAGE3="Grabando archivos de la configuracin..."
MESSAGE4="Por favor, seleccione el directorio para los archivos de la configuracin del ahorro."
E1="Configuracin personal (escritorio, programas)"
E2="Configuracin de Red y Celliax"
E3="Configuracin del subsistema grfico (XF86Config)"
E4="Otras configuraciones del sistema (impresora, etc.)"
E5="Todos los archivos en el Downloads (${DESKTOPKB}kB)"
ERROR="No se pudo crear de configuracin de KNOPPIX. Puede ser elijido el CDrom?"
;;
*)
TITLE1="Create KNOPPIX configuration archive"
MESSAGE1="This program write two regular files (configs.tbz and knoppix.sh) in the root of the disk/partition (or USB key) you choose in the next screen.\nNothing else will be touched or modified on the hard disk, don't worry.\n\nChoose which configurations you want to be automatically reloaded next time you boot in the LiveCD:"
MESSAGE2="Please insert an empty DOS- or ext2-formatted, writable floppy disk."
MESSAGE3="Saving configuration archive..."
MESSAGE4="You can choose both Linux or Windows disk/partition. Please select disk/partition for saving configuration files (an USB key or disk will show up as /media/sda1 or similar):"
E1="Personal configuration (desktop, programs, Skype, Firefox, etc)"
E2="Network and Celliax settings (if you \"make installed\" Celliax from svn, saves its new binaries too, ~5MB)"
E3="Graphics subsystem settings (XF86Config, screen resolution, etc)"
E4="Other system configuration (printer etc.)"
E5="All files in the Downloads folder (${DESKTOPKB}kB)"
ERROR="The KNOPPIX configuration could NOT be saved. Try with another disk/partition"
;;
esac

$DIALOG --clear --title "$TITLE1" --checklist "$MESSAGE1" 22 100 9 p "$E1" on d "$E5" on 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;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="/media/fd0/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 "$?"
}

# Just displays the symlink target, does not actually cause the automounter to attempt starting a mount.
FLOPPYDIR="$(ls -ld /media/fd0 | awk '{print $NF}')"

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

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

PARTITIONS=""
# Directory selector
for i in `awk '/^\/dev\/([hs]d|ub)[a-z][0-9].*\/media\/([hs]d|ub)[a-z][0-9]/{print $2}' /etc/fstab`; do
PARTITIONS="$PARTITIONS ${i} [Disk/Partition] off"
done
PARTITIONS="$PARTITIONS /media/fd0 [Floppy] off"

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

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

case "$DIRECTORY" in *floppy*|*fd0*)
DIRECTORY="$FLOPPYDIR"
KNOPPIXSH="$DIRECTORY/knoppix.sh"
while :; do
umountfloppy
$DIALOG --title "$TITLE1" --yesno "$MESSAGE2" 8 65 || bailout
echo "$FLOPPYDIR" | grep -q auto || mount -rw /media/fd0
[ "$?" = "0" ] && writescript "$KNOPPIXSH" && break
done
;;
*)
rm -f "$TMP.err"
mount | grep -q "$DIRECTORY" || mount -rw "$DIRECTORY" >"$TMP.err"
[ "$?" != "0" ] && { $DIALOG --title "$TITLE1" --msgbox "$ERROR `cat $TMP.err`" 10 75; bailout; }
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"
[ -n "$SAVEDESK" ] && for i in $HOME/Downloads; 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"
findchanged /usr/local/asterisk/etc /KNOPPIX/usr/local/asterisk/etc >>"$TMP"
findchanged /usr/local/asterisk/usr /KNOPPIX/usr/local/asterisk/usr >>"$TMP"
findchanged /usr/local/asterisk/var/lib /KNOPPIX/usr/local/asterisk/var/lib >>"$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

BOOTOPT="knoppix myconfig=$DIRECTORY"
AUTO="knoppix myconfig=scan"
case "$DIRECTORY" in *floppy*|*fd0*)
 BOOTOPT="knoppix floppyconfig"
 AUTO=""
esac

# More language-dependent Messages
case "$LANGUAGE" in
de*|at*|ch*)
[ -n "$AUTO" ] && AUTO=" bzw. \"$AUTO\" (automatische Suche)"
SUCCESS="Die KNOPPIX-Konfiguration wurde erfolgreich gespeichert. Ihre Konfigurationsdateien werden beim nchsten KNOPPIX-Bootvorgang in die Ramdisk restauriert automatik."
;;
es*)
[ -n "$AUTO" ] && AUTO=" o \"$AUTO\" (automatic)"
SUCCESS="La creacin del configuracin de KNOPPIX fue satisfactoria. Sus archivos de configuracin sern reinstalados en el siguiente arranque de KNOPPIX."
;;
*)
[ -n "$AUTO" ] && AUTO=", or \"$AUTO\" (automatic search)"
SUCCESS="Creation of the KNOPPIX configuration archive was successful.\n\nYour configuration files will be reinstalled to the ramdisk on next KNOPPIX boot.\n\nIf you want to boot without reinstalling those configurations, type at the boot prompt \"knoppix myconfig=no\".\n\nIf you will use this script to save another config in the future, be sure to choose the same disk/partition, so to overwrite this one.\n\nIf you used an USB disk or key, remember to connect it at boot ;)"
;;
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" 22 75 || $DIALOG --title "$TITLE1" --msgbox "$ERROR `cat $TMP.err`" 22 75

bailout
