#!/bin/bash
# knoppix-mkimage - create KNOPPIX home directory and configuration image
# (C) Klaus Knopper Feb 2005
# 한글메시지 번역 : 서민구, 신재훈
# Knoppix 한글 메시지 출력을 위한 코드 수정 : 신재훈

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

XDIALOG_HIGH_DIALOG_COMPAT=1
export XDIALOG_HIGH_DIALOG_COMPAT
#XDIALOG_FORCE_AUTOSIZE=1
#export XDIALOG_FORCE_AUTOSIZE

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

TMP="/tmp/knoppix-mkimage.tmp$$"

DIRECTORY=""

bailout(){
rm -f "$TMP" "$TMP.done" "$TMP.err"
[ -n "$DIRECTORY" ] && umount "$DIRECTORY" 2>/dev/null
exit 0
}

# Check if first 96k of file are zeros
iszero(){
ODSTRING="0000000 000000 000000 000000 000000 000000 000000 000000 000000
*
0300000"
[ "$(od -N 96k $1)" = "$ODSTRING" ]  && return 0 || return 1
}

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

# NTFS warnings
ntfsdisclaimer(){
case "$LANGUAGE" in
de*|at*|ch*)
NTFSTITLE="NTFS WARNUNG"
NTFSWARNING1="Linux untersttzt das NTFS-Dateisystem von Windows(TM) XP nur sehr eingeschrnkt, da der Hersteller seine Spezifikationen nicht vollstndig offenlegt. Allerdings ist es mglich, den Inhalt einer bereits angelegten Datei zu verndern. Das lsst sich fr das Einrichten virtueller Laufwerke auf NTFS-Partitionen nutzen.

WARNUNG: DIES IST EIN NEUES, NOCH EIN SEHR EXPERIMENTELLES FEATURE. FR DIE EINWANDFREIE FUNKTION KANN KEINE GARANTIE GEGEBEN WERDEN.
Mchten Sie weitermachen?"
NTFSWARNING2="WARNUNG (2): NTFS/Windows(TM) kann unerwartet reagieren, wenn Linux bei einem schreibbar eingebundenen NTFS Dateisystem nicht sauber beendet/heruntergefahren wird, oder beim Schreiben von Daten Fehler auftreten. In diese Fllen wird Windows beim Start \"SCANDISK\" oder \"CHKDSK\" starten, um die Konsistenz der Partition zu berprfen. Normalerweise treten dabei keine Fehler auf, sofern das Dateisystem nicht schon vor dem Start von Linux in einem defekten Zustand war. Unter ungnstigen Umstnden knnten jedoch Daten verlorengehen.

Wollen Sie immer noch weitermachen?"
NTFSWARNING3="WARNUNG (3): Haben Sie alle wichtigen und unersetzlichen Daten von der Partition, auf der Sie ein KNOPPIX-Image einrichten mchten, auf ein externes Medium gesichert, sind Backups vorhanden und sind Sie im Notfall in der Lage, die NTFS-Partition (und Windows) selbst wieder zu reparieren?"
;;
es*)
NTFSTITLE="AVISO SOBRE NTFS"
NTFSWARNING1="El sistema de ficheros NTFS/XP de Windows(TM) slo est parcialmente soportado por Linux, debido a las especificaciones tcnicas insuficientes proporcionadas por el fabricante. Pero existe soporte para sobreescribir el contenido de ficheros existentes, lo cual es til para crear discos \"virutales\" en particiones NTFS.

AVISO: ESTA CARACTERSTICA ES TOTALMENTE EXPERIMENTAL. NO HAY GARANTA DE QUE FUNCIONE EN SU SISTEMA.
Desea continuar?"
NTFSWARNING2="AVISO (2): NTFS/Windows(TM) puede reaccionar de formas inesperadas si Linux no se apaga de forma limpia despus de haber trabajado con sistemas de ficheros NTFS montados en modo escritura, o si hay errores edurante operaciones de escritura. En estos casos, Windows iniciar \"SCANDISK\" o \"CHKDSK\" para asegurarse de que los datos de la particin son consistentes. Normalmente no se producen errores durante la comprobacin, pero en casos ocasionales, se pueden perder datos.

An desea continuar?"
NTFSWARNING3="AVISO (3): Ha hecho una copia de todos los datos importantes de la particin que desea usar para la imagen de KNOPPIX en un soprte externo? Es usted capaz de, en el peor de los casos, reparar la particin NTFS (o Windows) por su cuenta?"
;;
*)
NTFSTITLE="NTFS WARNING"
NTFSWARNING1="The Windows(TM) NTFS/XP filesystem is only partly supported by Linux, because of insufficient technical specifications by the manufacturer. But there is support for overwriting file contents of existing files, which is useful for creating \"virtual disk drives\" on a NTFS partition.

WARNING: THIS IS YET A VERY EXPERIMENTAL FEATURE. THERE IS NO WARRANTY THAT IT WILl WORK FOR YOUR SYSTEM.
Do you want to continue?"
NTFSWARNING2="WARNING (2): NTFS/Windows(TM) can react in unexpected ways if Linux is not cleanly shut down after work when an NTFS filesystem is mounted in write mode, or if there are errors during write operations. In these cases, Windows will start \"SCANDISK\" or \"CHKDSK\" to make sure the partition data is in a consistent state. Usually no errors occur during the check, but in rare cases, data may be lost.

Do you still want to continue?"
NTFSWARNING3="WARNING (3): Have you made a copy of all important data from the partition you want to use for a KNOPPIX image, on external backup media? Are you able, in the worst case, to repair the NTFS partition (or Windows) on your own?"
;;
esac
$DIALOG --cr-wrap --defaultno --title "$NTFSTITLE" --yesno "$NTFSWARNING1" 16 75 || return 1
$DIALOG --cr-wrap --defaultno --title "$NTFSTITLE" --yesno "$NTFSWARNING2" 16 75 || return 1
$DIALOG --cr-wrap --defaultno --title "$NTFSTITLE" --yesno "$NTFSWARNING3" 10 75 || return 1 
return 0
}

HOMEKB="$(du -sk /ramdisk/. 2>/dev/null | awk '{print $1}')"

# Language-dependent Messages
case "$LANGUAGE" in
de*|at*|ch*)
TITLE1="Permanentes KNOPPIX Image anlegen"
MESSAGE1="Dieses Skript richtet ein permanentes Festplatten-Image fr den User \"knoppix\" auf Ihrer Festplatte oder einem Wechselmedium wie Memorystick, Compactflash oder ZIP-Medium ein. Hierdurch ist es mglich, Daten und persnliche Konfigurationen ber einen Reboot hinaus zu speichern. Per Bootoption, z.B. \"home=/mnt/uba1\" fr die erste Partition eines USB-Memorystick, knnen Sie beim Systemstart das permanente Heimverzeichnis wieder aktivieren. Die Bootoption \"home=scan\" durchsucht automatisch alle Partitionen und erkannten Speichermedien nach einem persistenten KNOPPIX-Heimverzeichnis.

Mchten Sie das Heimverzeichnis des Benutzers \"knoppix\" und/oder die Systemkonfiguration permanent speichern?"
MESSAGE2="Bitte whlen Sie die Partition, auf der Sie das Image anlegen mchten."
MESSAGE3="Hier befindet sich bereits eine KNOPPIX.IMG-Datei mit Daten. Mchten Sie die Datei formatieren und neu einrichten?
NEIN=Abbruch"
MESSAGE4="Dies ist eine NTFS-Partition. Da es hierfr vom Hersteller keinen Linux-Support gibt, der das direkte Schreiben auf die Partition ermglichen wrde, mssen Sie zunchst von Windows(TM) aus eine leere Image-Datei einrichten. Ein Programm hierfr finden Sie im Verzeichnis KNOPPIX auf Ihrer CD. WARNUNG: DIES IST EIN NEUES, EXPERIMENTELLES FEATURE. ES GIBT KEINE GARANTIE, DASS ALLES EINWANDFREI FUNKTIONIERT."
MESSAGE5="Bitte whlen Sie das Dateisystem fr das KNOPPIX image. ext3, reiserfs und xfs sind sog. \"journaling\" Dateisysteme und sehr robust gegen Fehler, bentigen aber leider 30MB mehr Platz, der nicht fr den eigentlichen Inhalt verwendet werden kann."
MESSAGE6="Dieses Image ist gerade in Benutzung, daher kann es nicht gelscht werden! Bitte booten Sie ggf. Knoppix neu, OHNE das Image $IMAGE einzubinden."
MESSAGE11="Diese Partition kann momentan nicht im Schreibmodus eingehngt werden. Das Programm wird beendet."
E1="Persnliche 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)"
SUCCESS="FERTIG!

Die KNOPPIX-Konfiguration wurde erfolgreich gespeichert. Ihre Konfigurationsdateien werden beim nchsten KNOPPIX-Bootvorgang in die Ramdisk restauriert, wenn Sie im Bootscreen \"knoppix floppyconfig\" (Diskette) bzw. \"knoppix myconfig=/mnt/verzeichnisname\" angeben."
ERROR="Leider konnte die KNOPPIX-Konfiguration NICHT gespeichert werden:"
MESSAGE_NO_PARTS="Keine passende Partition gefunden."
;;
ko)
TITLE1="KNOPPIX 홈 디렉토리 보존기능"
MESSAGE1="이 스크립트는 \"knoppix\" 계정을 위하여 영구적인 가상 하드 디스크 이미지를 하드디스크 또는 USB 메모리와 같은 저장매체에 생성합니다. 이 기능을 사용하여, 개인 데이터와 설정 파일이 재부팅 후에도 보존되도록 할 수 있습니다. 예를 들어, 부트 옵션 \"home=/dev/uba1\"은 USB 메모리의 첫번째 파티션을 시스템 시작시에 홈 디렉토리로 설정합니다. 또한 부트 옵션 \"home=scan\"을 통해 자동으로 모든 저장매체의 홈 디렉토리 이미지를 검색하도록 할 수 있습니다.\n

\"knoppix\" 계정을 위한 영구적인 홈 디렉토리 이미지 또는 시스템 설정 아카이브를 생성하시겠습니까?"
MESSAGE2="이미지를 생성할 파티션을 선택"
MESSAGE3="해당 파티션에는 이미 Knoppix 이미지가 존재합니다. 이를 삭제/포맷 하시겠습니까?"
MESSAGE4="NTFS 파티션입니다. NTFS 파일시스템에 쓰기 동작을 수행하는데 필요한 벤더로부터의 공식적인 지원이 없으므로, 먼저 Windows(TM)에서 비어있는 이미지 파일을 생성해야합니다. CD안에 있는 KNOPPIX 디렉토리에서 이에 필요한 프로그램을 찾을 수 있습니다. 주의: 이 기능은 실험단계에 있습니다. 정상적인 작동을 보장하지 않습니다."
MESSAGE5="KNOPPIX 이미지를 위한 파일 시스템을 선택하십시오. ext3, reiserfs, xfs 는 저널링 파일 시스템으로서 복구 기능이 뛰어납니다. 그러나 저널을 기록하는데 추가적으로 30MB의 공간이 소요되며, 이 공간은 사용자의 데이터를 저장하는데 사용할 수 없습니다."
MESSAGE6="이 이미지는 현재 사용중입니다. 만약 이 이미지를 삭제/포맷 하고 싶다면 $IMAGE 이미지를 비활성화 한 채로 Knoppix를 재부팅하십시오."
MESSAGE11="이 하드디스크 파티션은 읽기-쓰기 모드로 마운트 될 수 없습니다."
E1="개인 설정 (데스크탑, 프로그램)"
E2="네트워크 설정 (LAN, 모뎀, ISDN, ADSL)"
E3="X 환경 설정 (XF86Config)"
E4="기타 시스템 설정 (프린터 등)"
E5="데스크탑 상의 모든 파일 (${DESKTOPKB}kB)"
SUCCESS="성공!\n
KNOPPIX 환경 설정 저장이 성공적으로 이루어졌습니다. 다음 KNOPPIX 부팅시에 부트 프롬프트에서 부팅옵션 \"knoppix floppyconf\" 또는 \"knoppix myconfig=/mnt/directoryname\"를 입력하시면, 설정 파일이 램디스크에 재설치 되도록 할 수 있습니다."
ERROR="KNOPPIX 환경 설정 저장에 실패하였습니다:"
MESSAGE_NO_PARTS="적절한 파티션을 찾지 못하였습니다."
;;
*)
TITLE1="Create persistent KNOPPIX home directory"
MESSAGE1="This script creates a persistent virtual harddisk image for the \"knoppix\" account on your harddisk or on a changeable medium like memory sticks, compact flash or zip media. Using this features makes it possible to store personal data and config files permanently over a reboot. The boot option \"home=/dev/uba1\", for the first partition of a USB memory stick as example, activates the persistent home directory at system startup. You can also let KNOPPIX scan all autodetected storage devices using the boot option \"home=scan\".

Do you want to create a persistent home directory or system config archive for the \"knoppix\" user?"

MESSAGE2="Please select a partition for creating the image:"
MESSAGE3="There is already a Knoppix image present on this partition. Would like to delete/format it?"
MESSAGE4="This is an NTFS partition. Because there is no vendor support for Linux that would allow writing directly to such a file system, you will first have to create an empty image file from within Windows(TM). You can find a program for this in the KNOPPIX directory on your CD. PLEASE BE AWARE THAT THIS IS A NEW YET A VERY EXPERINEMTAL FEATURE. THERE IS NO GUARANTEE THAT IT WILL WORK."
MESSAGE5="Please chose the filesystem for the KNOPPIX image. ext3, reiserfs and xfs are journaling file systems and are very robust to errors, but require an additional amount of about 30MB disk space for the journal that cannot be used by actual content."
MESSAGE6="This image is currently in use. If you want to delete/reformat it, please reboot Knoppix first, without activating the image $IMAGE."
MESSAGE11="This harddisk partition cannot be mounted in read-write mode currently, sorry."
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)"
SUCCESS="SUCCESS!

Creation of KNOPPIX configuration floppy was successful. Your configuration files will be reinstalled to the ramdisk on next KNOPPIX boot if you specify \"knoppix floppyconf\" (floppy disk), or \"knoppix myconfig=/mnt/directoryname\" at the boot prompt."
ERROR="The KNOPPIX configuration could NOT be saved:"
MESSAGE_NO_PARTS="No suitable partitions could be found."
;;
esac

$DIALOG --cr-wrap --clear --title "$TITLE1" --yesno "$MESSAGE1" 18 75 || bailout

# Build partition selector
PARTITIONS=""
count=0
for i in `awk '/^\/dev\/([hs]d|ub)[a-z].*\/mnt\/([hs]d|ub)[a-z]/{print $1}' /etc/fstab`; do
 fstype="$(awk "/^${i//\//\\/} /"'{print $3;exit}' /etc/fstab)"
 case "$fstype" in reiserfs|ext3|ext2|xfs|vfat|ntfs) ;; *) continue ;; esac
 size="$(awk '{if($NF=="'"${i##*/}"'"){print $3; exit}}' /proc/partitions)" # kB
 size="$((size/1024))MB" # MB
 PARTITIONS[$((count++))]="${i}"
 case "$i" in
  *hda*) PARTITIONS[$((count++))]="IDE  HD Partition [$fstype] ($size)" ;;
  *sda*) PARTITIONS[$((count++))]="SCSI HD Partition [$fstype] ($size)" ;;
  *uba*) PARTITIONS[$((count++))]="USB  HD Partition [$fstype] ($size)" ;;
      *) PARTITIONS[$((count++))]="Unknown [$fstype] ($size)" ;;
 esac
 PARTITIONS[$((count++))]="off"
done
[ -z "$PARTITIONS" ] && { $DIALOG --cr-wrap --clear --title "$TITLE1" --msgbox "$ERROR $MESSAGE_NO_PARTS" 10 75; bailout; }

DIRECTORY=""
PARTITION=""
while [ -z "$PARTITION" -o -z "$DIRECTORY" -o ! -e "$DIRECTORY" ]; do
rm -f "$TMP"
$DIALOG --cr-wrap --clear --title "$TITLE1" --radiolist "$MESSAGE2" 18 75 9 "${PARTITIONS[@]}" 2>"$TMP" || bailout
PARTITION="$(<$TMP)"
DIRECTORY="/mnt/${PARTITION##/dev/}"
done

mount | grep -q "$DIRECTORY" || mount -r "$DIRECTORY" 2>"$TMP.err"
[ "$?" != "0" ] && { $DIALOG --cr-wrap --title "$TITLE1" --msgbox "$ERROR `cat $TMP.err`" 10 75; bailout; }
NTFS=""
mount | grep -q "$DIRECTORY.*ntfs"
[ "$?" = "0" ] && NTFS=true

IMAGE="$(ls -1d $DIRECTORY/[Kk][Nn][Oo][Pp][Pp][Ii][Xx].[Ii][Mm][Gg])"

# Language-dependent Messages
case "$LANGUAGE" in
de*|at*|ch*)
MESSAGE6="Dieses Image ist gerade in Benutzung, daher kann es nicht gelscht werden! Bitte booten Sie ggf. Knoppix neu, OHNE das Image $IMAGE einzubinden."
;;
ko)
MESSAGE6="현재 사용중인 이미지입니다. 만약 이 이미지를 삭제/포맷 하고 싶다면, $IMAGE 이미지를 비활성화 한 상태에서 Knoppix를 재부팅 하십시오."
;;
*)
MESSAGE6="This image is currently in use. If you want to delete/reformat it, please reboot Knoppix first, without activating the image $IMAGE."
;;
esac

if [ -n "$IMAGE" -a -f "$IMAGE" ]; then
 mount | grep -q "$IMAGE" && { $DIALOG --cr-wrap --title "$TITLE1" --msgbox "$MESSAGE6" 10 75; bailout; }
 if iszero "$IMAGE"; then
  true
 else
  $DIALOG --cr-wrap --clear --title "$TITLE1" --defaultno --yesno "$MESSAGE3" 8 75 || bailout
 fi
else
 IMAGE=""
 [ -n "$NTFS" ] && { $DIALOG --cr-wrap --title "$TITLE1" --msgbox "$MESSAGE4" 12 75; bailout; }
fi

# Here, we have either NO image, or an existing image that is OK to overwrite.
if [ -n "$NTFS" ]; then
ntfsdisclaimer || bailout
fi

# Now, make partition writable
mount -o remount,rw "$DIRECTORY" || { $DIALOG --cr-wrap --msgbox "$MESSAGE11" 10 75; bailout; }

# More language-dependent Messages
case "$LANGUAGE" in
de*|at*|ch*)
MESSAGE7="Mchten Sie das Image mit AES256 (=Advanced Encryption Standard 256bit, s.a. http://csrc.nist.gov/encryption/aes/) verschlsseln? Hierzu ist die Eingabe eines sehr langen Passwortes beim Einrichten sowie beim Einbinden des Verzeichnisses beim Systemstart erforderlich. NEIN=unverschlsselt"
MESSAGE8="Bitte geben Sie die gewnschte Gre des Knoppix-Image in MB an (aktuell belegt: $HOMEKB Kilobyte, verfgbar:"
MESSAGE9="Formatiere Image-Datei und kopiere Daten..."
MESSAGE10="Lege Datenbereich fr Linux an..."
SUCCESS="Image-Datei wurde erfolgreich mit dem Linux ext2 Dateisystem formatiert, und Ihre Heimverzeichnis-Daten sowie System-Konfigurationsdateien wurden darauf transferiert.

Sie knnen jetzt Ihren Computer neu starten, und beim Booten sollte KNOPPIX das Image automatisch finden. Alternativ knnen Sie beim boot:-Prompt \"knoppix home=$PARTITION\" oder \"knoppix home=scan\" angeben."
;;
ko)
MESSAGE7="홈 디렉토리를 AES256 (Advanced Encryption Standard. http://csrc.nist.gov/encryption/aes/ 참조)로 암호화 하시겠습니까? 만약 네(YES)로 응답할 경우, 홈 디렉토리 생성과 부팅시에 긴 비밀번호를 입력해야합니다."
MESSAGE8="MB 단위로 원하는 영구적인 홈 디렉토리 이미지의 크기를 입력하십시오 (현재 사용중: $HOMEKB kB, 사용가능)"
MESSAGE9="Knoppix-Image 포맷 및 데이터 복사중..."
MESSAGE10="리눅스 파일 시스템 준비중..."
SUCCESS="Knoppix-Image 가 ext2 파일시스템으로 성공적으로 포맷되었고 홈 디렉토리와 시스템 설정 데이터가 전송되었습니다.\n
이제 컴퓨터를 재부팅해서 Knoppix가 이미지를 자동으로 검색하도록 할 수 있습니다. 다른 방법으로 boot: 프롬프트에서 부트옵션 \"knoppix home=$PARTITION\" 또는 \"knoppix home=scan\"를 입력하여 이미지 파일의 경로를 직접 지정할 수 있습니다."
;;
*)
MESSAGE7="Do you want to save your home directory encrypted with AES256 (Advanced Encryption Standard, see http://csrc.nist.gov/encryption/aes/)? If yes, you will have to specify a very long password at homedir creation and boot time."
MESSAGE8="Please enter the desired size of your persistent homedir in MB (currently used: $HOMEKB kB, available:"
MESSAGE9="Formatting Knoppix-Image and copying data..."
MESSAGE10="Preparing for Linux filesystem..."
SUCCESS="The Knoppix-Image has been succeessfully formatted with the Linux ext2 filesystem, and your home directory and system configuration data has been transferred to it.

You may now reboot your computer, and KNOPPIX should find the image automatically. Alternatively, type \"knoppix home=$PARTITION\" or \"knoppix home=scan\" at the KNOPPIX boot: prompt."
;;
esac

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

# Stop status bar
killgauge(){
touch "$TMP.done" ; wait ; rm -f "$TMP.done"
}

ENCRYPTION=""
$DIALOG --cr-wrap --clear --title "$TITLE1" --defaultno --yesno "$MESSAGE7" 9 75 && ENCRYPTION="AES256"


SIZEMB=0
if [ -z "$NTFS" ]; then
 [ -n "$IMAGE" ] && rm -f "$IMAGE"
 IMAGE="$DIRECTORY/knoppix.img"
 AMOUNT=0
 AVAIL="$(df -m $DIRECTORY/. | tail -1 | awk '{print $4}')"
 until [ "$AMOUNT" -ge 1 -a "$AMOUNT" -le "$AVAIL" ] 2>/dev/null; do
  $DIALOG --cr-wrap --clear --title "$TITLE1" --inputbox "$MESSAGE8 $AVAIL MB)" 10 62 "100" 2>"$TMP" || bailout
  AMOUNT="$(<$TMP)"
 done
 gauge "$MESSAGE10" &
 IF_DEVICE=/dev/zero
 [ -n "$ENCRYPTION" ] && IF_DEVICE=/dev/urandom
 dd if="$IF_DEVICE" of="$IMAGE" bs=1M count="$AMOUNT" || { killgauge; sleep 2; bailout; }
 killgauge
else
 # NTFS, overwrite file with random data of exactly the same size
 [ -z "$IMAGE" ] && bailout # This should never happen
 SIZEMB="$(ls -l $IMAGE | awk '{print $5}')"
 SIZEMB="$(($SIZEMB/1024/1024))"
 [ "$SIZEMB" -ge 100 ] || bailout # This should also never happen
fi

# New: chose filesystem
# unfinished yet
# while [ -z "$FS" ]; do
# rm -f "$TMP"
# $DIALOG --cr-wrap --clear --title "$TITLE1" --radiolist "$MESSAGE5" 18 75 9 "ext2" "Ext2 Filesystem" on "ext3" "Ext3 (journaling) Filesystem" off "reiserfs" "ReiserFS (journaling) Filesystem" off 2>"$TMP" || bailout
# FS="$(<$TMP)"
# done

findfreeloop(){
i=0
for i in 0 1 2 3 4 5 6 7; do
LOOP="/dev/loop$i"
losetup "$LOOP" >/dev/null 2>&1 || { echo "$LOOP"; return 0; }
done
return 1
}

getpassword(){
case "$LANGUAGE" in
de*|at*|ch*)
HEADER="AES256 Verschlsselungs-Passwort (Minimum 20 Zeichen!)"
ENTER="Eingabe:"
AGAIN="Noch einmal, um sicherzugehen:"
;;
ko)
HEADER="AES256 암호화형식 비밀번호 (최소 20자 이상!)"
ENTER="비밀번호 입력:"
AGAIN="확인을 위해 다시 입력:"
;;
*)
HEADER="AES256 encryption password (minimum 20 characters!)"
ENTER="Enter:"
AGAIN="Again, just to be sure:"
;;
esac
PASS1=""
PASS2=""
until [ -n "$PASS1" -a "$PASS1" = "$PASS2" ]; do
rm -f "$TMP.pass"
if [ "$DIALOG" = "Xdialog" ]; then
Xdialog --title "$TITLE1" --password --password --2inputsbox "$HEADER" 15 60 "$ENTER" "" "$AGAIN" "" 2>"$TMP.pass" || bailout
PASSWORDS="$(<$TMP.pass)"
PASS1="${PASSWORDS%%/*}"
PASS2="${PASSWORDS##*/}"
else
dialog --title "$HEADER" --insecure --passwordbox "$ENTER" 8 65 "" 2>"$TMP.pass" || bailout
PASS1="$(<$TMP.pass)"
dialog --title "$HEADER" --insecure --passwordbox "$AGAIN" 8 65 "" 2>"$TMP.pass" || bailout
PASS2="$(<$TMP.pass)"
fi
done
rm -f "$TMP.pass"
echo "$PASS1" >&2
}

LOOPDEV="$(findfreeloop)" || bailout
FORMAT=""

if [ -n "$ENCRYPTION" ]; then
 getpassword 2>"$TMP"
 losetup -p0 -e "$ENCRYPTION" "$LOOPDEV" "$IMAGE" 2>"$TMP.err" <"$TMP"
else 
 losetup "$LOOPDEV" "$IMAGE" 2>"$TMP.err"
fi

if [ "$?" != "0" ]; then
 rm -f "$TMP"
 $DIALOG --cr-wrap --title "$TITLE1" --msgbox "$ERROR `cat $TMP.err`" 10 75
 bailout
fi

rm -f "$TMP"
# Start progress display and copy data
gauge "$MESSAGE9" &
[ -n "$NTFS" ] && dd if=/dev/urandom of="$LOOPDEV" bs=1M count="$SIZEMB" 
mke2fs -m0 "$LOOPDEV" 2>"$TMP.err" || { killgauge; $DIALOG --cr-wrap --title "$TITLE1" --msgbox "$ERROR `cat $TMP.err`" 10 75; bailout; }
mkdir -p /tmp/knxhome
mount -t ext2 "$LOOPDEV" /tmp/knxhome 2>"$TMP.err" && rsync --exclude /ramdisk/var/tmp/ --exclude /ramdisk/etc/mtab --exclude /etc/mtab -Ha /ramdisk/ /tmp/knxhome 2>"$TMP.err" || { umount /tmp/knxhome 2>/dev/null; killgauge; $DIALOG --cr-wrap --title "$TITLE1" --msgbox "$ERROR `cat $TMP.err`" 10 75; bailout; }

# Save knoppix.sh script ?
# Rather add some links in the network/printer configuration scripts that go to the pesistent homedir.

# Finish
umount /tmp/knxhome
[ -n "$LOOPDEV" ] && losetup -d "$LOOPDEV"
umount "$DIRECTORY" 2>/dev/null
killgauge

$DIALOG --cr-wrap --title "$TITLE1" --msgbox "$SUCCESS" 17 65

bailout
