#!/bin/bash

#
# Knoppix install on hard disk
# knx-hdinstall 0.39
# 01/2003 Christian Perle <perle@itm.tu-clausthal.de>
#
# 06/2003 update by Fabian Franz <knx-hdinstall@fabian-franz.de>
#
# Contributors:
# Eduard Bloch <inet@zombie.inka.de> better lilo.conf support
# Erik Ringius <erik.ringius@telia.com> swedish translation
# Erik Schanze <schanzi_@gmx.de> extended swap selection
# Fabian Franz <fabianfranz@gmx.de> progress bar, more filesystem types
# Florent Beranger <cosmicflo@tuxfamily.org> french translation
# Klaus Knopper <knopper@linuxtag.org> knoppix specific changes/bugfixes
# Luis Llorente <luis.llorente@hispalinux.es> spanish translation
#
# This software is released under the GPL. There is NO WARRANTY.
# (see http://www.gnu.org/licenses/gpl.html)
#
# TODO:
# separate /boot partition
# optional automounter support
# "no cloop" install (extract_compressed_fs, requires doubled disk space)
#

SVERSION="0.39"

# get the kernel command line
CMDLINE="$(cat /proc/cmdline)"

# some functions borrowed from knoppix-autoconfig

stringinstring()
{
  case "$2" in *$1*) return 0;; esac
  return 1
}

getbootparam()
{
  stringinstring "$1=" "$CMDLINE" || return 1
  result="${CMDLINE##*$1=}"
  result="${result%%[ 	]*}"
  echo "$result"
  return 0
}

checkbootparam()
{
  stringinstring "$1" "$CMDLINE"
  return "$?"
}

rotdash()
{
  p=$1
  while [ -d /proc/$p ]
  do
    echo -n '/' ; usleep 100000
    echo -n '-' ; usleep 100000
    echo -n '\' ; usleep 100000
    echo -n '|' ; usleep 100000
  done
}

progressbar()
{
  {
  TOTAL=2100
  p=$1
  while [ -d /proc/$p ]
  do
    PROGRESS=$(df -m /mnt/target | awk '/target/{print $3}')
    echo $[PROGRESS*100/TOTAL]
    sleep 10
  done
  } | $DIA --backtitle "$BT" --title "$T1" --gauge "$M2" 8 60 0
}

# X or text console
case "`tty`" in
  /dev/tty[1-8])
    MODE=text
    DIA=dialog
    ;;
  /dev/pts/*|/dev/ttyp*)
    MODE=x
    export XDIALOG_HIGH_DIALOG_COMPAT=1
    [ -x /usr/bin/gdialog ] && DIA=gdialog
    [ -x /usr/bin/Xdialog ] && DIA=Xdialog
    [ $DIA = dialog ] && MODE=text
    ;;
  *)
    MODE=text
    DIA=dialog
    ;;
esac
# text mode if DISPLAY is not set
if [ -z "$DISPLAY" ] ; then
  MODE=text
  DIA=dialog
fi

# mount point for root filesystem
TR="/mnt/target"
# mount points for loop-mounts
TL1="/mnt/l1"
TL2="/mnt/l2"
# directory for templates
TM="$TR/templates"
# default hostname
DEFHNAME="box"
# default vga mode
DEFVGA="791"

if [ $UID != 0 ] ; then
  echo "This script requires root privileges."
  exit 0
fi

TMP="/tmp/hdinst.tmp.$$"
[ -f /etc/sysconfig/i18n ] && . /etc/sysconfig/i18n
ORIG_LANG="$LANG"
ORIG_LANGUAGE="`getbootparam lang`"
ORIG_LC_ALL="$LC_ALL"
# throw away locale settings
export LANG=C
export LANGUAGE=C
export LC_ALL=C
umask 022
killall dhcpcd >/dev/null 2>&1
killall -9 pump >/dev/null 2>&1
killall automount >/dev/null 2>&1
swapoff -a >/dev/null 2>&1
# unmount anything in /mnt
while read x mnt x
do
  case "$mnt" in
    /mnt*)
      umount $mnt >/dev/null 2>&1
      ;;
    *) ;;
  esac
done < /proc/mounts

case "$ORIG_LANGUAGE" in
de|at|ch)
BT="StreamBOX Installation"
M1="Dieses Skript hilft bei der Installation \
von StreamBOX auf Festplatte. Beachten Sie, \
dass sich knx-hdinstall noch in der \
Entwicklungsphase befindet. Für Datenverluste oder Hardwareschäden \
übernimmt der Autor Christian Perle und KNOPPER.NET keine Haftung."
;;
es)
BT="Instalación de StreamBOX"
M1="Este script ayuda en la instalación de StreamBOX\
en el disco duro. Nótese que knx-hdinstall está todavía en \
desarrollo. El autor no toma ninguna responsabilidad \
en caso de pérdida de datos o daño del hardware."
;;
fr)
BT="Installation de StreamBOX"
M1="Ce script aide à installer StreamBOX\
sur un disque dur. Notez que knx-hdinstall est en phase de développement. \
L'auteur Christian Perle et KNOPPER.NET se dégagent de toute responsabilité \
en cas de perte de données ou dommage matériel."
;;
se)
BT="StreamBOX installation"
M1="Detta skript är en hjälp vid installation av StreamBOX\
på en hårddisk. Observera att knx-hdinstall är under utveckling. \
Författaren Christian Perle och KNOPPER.NET avsäger sig allt ansvar \
för alla skador, förlorade data och skador på hårdvara."
;;
*)
BT="StreamBOX Install"
M1="This script helps installing StreamBOX\
on a hard disk. Note that knx-hdinstall is still under \
development. The author Christian Perle and KNOPPER.NET take no responsibility \
for data loss or hardware damage."
;;
esac

$DIA --backtitle "$BT" --title "knx-hdinstall $SVERSION" --msgbox "$M1" 16 45

# check the templates
case "$ORIG_LANGUAGE" in
de|at|ch)
T1="Datei fehlt"
M1="Die vom Skript benötigte Datei knx-templates-$SVERSION.tgz wurde nicht gefunden oder ist beschädigt. Das Skript wird beendet."
;;
es)
T1="Archivo no encontrado"
M1="El archivo knx-templates-$SVERSION.tgz requerido, no está o está corrupto. El script finalizará."
;;
fr)
T1="Fichier manquant"
M1="Le fichier knx-templates-$SVERSION.tgz requis est manquant ou corrompu. Le script va être terminé."
;;
se)
T1="Fil saknas"
M1="Filen knx-templates-$SVERSION.tgz saknas eller är skadad. Skriptet avbryts."
;;
*)
T1="Missing file"
M1="The required file knx-templates-$SVERSION.tgz is missing or corrupted. The script will be terminated."
;;
esac
INSTDATA=""
for x in "`dirname $0`/knx-templates-$SVERSION.tgz" \
  "/usr/local/lib/knx-templates-$SVERSION.tgz"
do
  if [ -z "$INSTDATA" ] ; then
    tar tzf "$x" >/dev/null 2>&1
    [ $? = 0 ] && INSTDATA="$x"
  fi
done
if [ -z "$INSTDATA" ] ; then
  $DIA --backtitle "$BT" --title "$T1" --msgbox "$M1" 15 60
  rm -f $TMP
  exit 0
fi

# valid partitioning: min. 2.2 GB file system, min. 128 MB swap
FSMIN=2200
SWAPMIN=128
# "no cloop" method requires more space
NCLOOPFSMIN=4400

# size of initrd: 2.5 MB
INSIZE=2500

# select hard disk for partitioning
> $TMP
NUMHD=0
if [ -f /proc/partitions ] ; then
  while read x x x p x
  do
    case "$p" in
      hd?)
        if [ "`cat /proc/ide/$p/media`" = "disk" ] ; then
          echo "$p `tr ' ' _ </proc/ide/$p/model`" >> $TMP
          NUMHD=$[NUMHD+1]
        fi
        ;;
      sd?)
        x="`scsi_info /dev/$p | grep MODEL | tr ' ' _`"
        x=${x#*\"}
        x=${x%\"*}
        echo "$p $x" >> $TMP
        NUMHD=$[NUMHD+1]
        ;;
      *) ;;
    esac
  done < /proc/partitions
fi
HARDDISKS="`cat $TMP`"
case "$ORIG_LANGUAGE" in
de|at|ch)
T1="Partitionieren"
M1="Wählen Sie eine Festplatte aus (Leertaste zum Ankreuzen):"
;;
es)
T1="Particionar el disco duro"
M1="Seleccione un disco duro (La barra espaciadora selecciona):"
;;
fr)
T1="Partitionnement"
M1="Choisissez un disque dur (touche Espace pour choisir):"
;;
se)
T1="Partitionering av hårddisk"
M1="Välj en hårddisk (Välj med mellanslagstangenten):"
;;
*)
T1="Partition hard disk"
M1="Choose a hard disk (Space bar selects):"
;;
esac
$DIA --backtitle "$BT" --title "$T1" --radiolist "$M1" 16 60 $NUMHD \
  $(echo "$HARDDISKS" | while read p model ; do echo "$p" "$model" off ; done) \
  2> $TMP
HDCHOICE="`cat $TMP`"
case "$ORIG_LANGUAGE" in
de|at|ch)
M1="Sie haben keine Festplatte ausgewählt. Das Skript wird beendet."
;;
es)
M1="No se ha seleccionado un disco duro. El script finalizará."
;;
fr)
M1="Aucun disque dur choisi. Le script va être terminé."
;;
se)
M1="Ingen hårddisk vald. Skriptet avbryts."
;;
*)
M1="No hard disk chosen. The script will be terminated."
;;
esac
if [ -z "$HDCHOICE" ] ; then
  $DIA --backtitle "$BT" --title "$T1" --msgbox "$M1" 15 40
  rm -f $TMP
  exit 0
fi
x=$(fdisk -l /dev/$HDCHOICE 2>/dev/null | grep " heads.* sectors.* cylinders")
HDS=${x%% heads*}
HDS=${HDS##* }
SECT=${x%% sectors*}
SECT=${SECT##* }
CYLS=${x% cylinders}
CYLS=${CYLS##* }
case "$ORIG_LANGUAGE" in
de|at|ch)
M1="Sie haben /dev/$HDCHOICE gewählt. \
Die Platte hat eine Kapazität von \
$[CYLS*HDS*SECT/2048] MB. \
Das Partitionierungsprogramm \
cfdisk wird jetzt gestartet."
;;
es)
M1="Disco duro /dev/$HDCHOICE seleccionado. \
Capacidad de este dispositivo: \
$[CYLS*HDS*SECT/2048] MB. \
Ahora se arrancará la herramienta cfdisk \
de particionado."
;;
fr)
M1="Le disque dur /dev/$HDCHOICE a été choisi. \
Sa capacité est de: \
$[CYLS*HDS*SECT/2048] MB. \
L'outil de partitionnement \
cfdisk va être lancé maintenant."
;;
se)
M1="Hårddisken /dev/$HDCHOICE är vald. \
Storleken är: \
$[CYLS*HDS*SECT/2048] MB. \
Partitioneringsprogrammet \
cfdisk startas nu."
;;
*)
M1="Hard disk /dev/$HDCHOICE chosen. \
Capacity of this device: \
$[CYLS*HDS*SECT/2048] MB. \
The partitioning tool \
cfdisk will be launched now."
;;
esac
$DIA --backtitle "$BT" --title "$T1" --msgbox "$M1" 15 40
if [ $MODE = text ] ; then
  (
  LANG="$ORIG_LANG"
  LANGUAGE="$ORIG_LANGUAGE"
  LC_ALL="$ORIG_LC_ALL"
  cfdisk /dev/$HDCHOICE
  )
else
  (
  LANG="$ORIG_LANG"
  LANGUAGE="$ORIG_LANGUAGE"
  LC_ALL="$ORIG_LC_ALL"
  xterm -fn 10x20 -e cfdisk /dev/$HDCHOICE
  )
fi

# swap: yes or no
case "$ORIG_LANGUAGE" in
de|at|ch)
T1="Virtueller Speicher (Swap)"
M1="Soll eine Swap-Partition verwendet werden (empfohlen)?"
;;
es)
T1="Memoria virtual (swap)"
M1="Quiere utilizar una partición de memoria virtual (recomendado)?"
;;
fr)
T1="Mémoire virtuelle (swap)"
M1="Voulez-vous utiliser une partition de swap (recommandé)?"
;;
se)
T1="Virtuellt minne på hårddisk (swap)"
M1="Vill du ha en swap partition (rekommenderas)?"
;;
*)
T1="Virtual memory (swap)"
M1="Do you want to use a swap partition (recommended)?"
;;
esac
$DIA --backtitle "$BT" --title "$T1" --yesno "$M1" 15 60
x=$?
if [ $x = 0 ] ; then
  # select swap partition
  > $TMP
  # search the current hard disk first
  SWHDCHOICE=$HDCHOICE
  fdisk -l /dev/$SWHDCHOICE | grep "^/dev.*Linux swap$" |
  while read dev x x size x
  do
    size=${size%+}
    echo $dev $[size/1024]_MB off >> $TMP
  done
  NUMSWAP="`wc -l <$TMP`"
  SWAPART="`cat $TMP`"

  # ask for another hard disk, if no swap partition was found and more
  # than one hard disk is present
  while [ $NUMSWAP = 0 -a $NUMHD -gt 1 ]
  do
    case "$ORIG_LANGUAGE" in
    de|at|ch)
    M1="Keine Swappartition auf der aktuellen Platte gefunden. Wählen Sie eine andere Festplatte aus (Leertaste zum Ankreuzen):"
    ;;
    fr)
    M1="Aucune partition de swap n'a été trouvée sur le disque dur courant. Merci de choisir un autre disque dur (touche Espace pour choisir):"
    ;;
    se)
    M1="Hittade ingen swappartition på den här hårddisken. Välj en annan hårddisk. (Välj med mellanslagstangenten):"
    ;;
    *)
    M1="No swap partition could be found on the current hard disk. Choose another hard disk (Space bar selects):"
    ;;
    esac
    $DIA --backtitle "$BT" --title "$T1" --radiolist "$M1" 16 60 $NUMHD \
      $(echo "$HARDDISKS" | while read p model ; do echo "$p" "$model" off ; done) \
        2> $TMP
    SWHDCHOICE="`cat $TMP`"
    case "$ORIG_LANGUAGE" in
    de|at|ch)
    M1="Sie haben keine Festplatte ausgewählt. Das Skript wird beendet."
    ;;
    fr)
    M1="Aucun disque dur choisi. Le script va être terminé."
    ;;
    se)
    M1="Ingen hårddisk vald. Skriptet avbryts."
    ;;
    *)
    M1="No hard disk chosen. The script will be terminated."
    ;;
    esac
    if [ -z "$SWHDCHOICE" ] ; then
      $DIA --backtitle "$BT" --title "$T1" --msgbox "$M1" 15 40
      rm -f $TMP
      exit 0
    fi
    > $TMP
    fdisk -l /dev/$SWHDCHOICE | grep "^/dev.*Linux swap$" |
    while read dev x x size x
      do
      size=${size%+}
      echo $dev $[size/1024]_MB off >> $TMP
    done
    NUMSWAP="`wc -l <$TMP`"
    SWAPART="`cat $TMP`"
  done
  # no swap partition found, abort
  if [ $NUMSWAP = 0 ] ; then
    case "$ORIG_LANGUAGE" in
    de|at|ch)
    T1="Swap einrichten"
    M1="Es wurde keine Swap-Partition auf der gewählten Platte gefunden. Das Skript wird beendet."
    ;;
    es)
    T1="Instalar swap"
    M1="No se pudo encontrar una partición swap en el disco duro elegido. El script finalizará."
    ;;
    fr)
    T1="Mise en place de la swap"
    M1="Aucune partition de swap n'a été trouvée sur le disque dur courant. Le script va être terminé."
    ;;
    se)
    T1="Installera swap"
    M1="Hittade ingen swappartition på den valda hårddisken. Skriptet avbryts."
    ;;
    *)
    T1="Set up swap"
    M1="No swap partition could be found on the chosen hard disk. The script will be terminated."
    ;;
    esac
    $DIA --backtitle "$BT" --title "$T1" --msgbox "$M1" 15 40
    rm -f $TMP
    exit 0
  fi
  case "$ORIG_LANGUAGE" in
  de|at|ch)
  T1="Swap einrichten"
  M1="Wählen Sie die Swap-Partition aus:"
  ;;
  es)
  T1="Instalar swap"
  M1="Elija una partición swap:"
  ;;
  fr)
  T1="Mise en place de la swap"
  M1="Choisissez une partition de swap:"
  ;;
  se)
  T1="Installera swap"
  M1="Välj en swap partition:"
  ;;
  *)
  T1="Set up swap"
  M1="Choose a swap partition:"
  ;;
  esac
  $DIA --backtitle "$BT" --title "$T1" --radiolist "$M1" 16 60 $NUMSWAP \
    $SWAPART 2> $TMP
  SWCHOICE="`cat $TMP`"
  if [ -z "$SWCHOICE" ] ; then
    case "$ORIG_LANGUAGE" in
    de|at|ch)
    M1="Sie haben keine Partition ausgewählt. Das Skript wird beendet."
    ;;
    es)
    M1="No se ha seleccionado ninguna partición swap. El script finalizará."
    ;;
    fr)
    M1="Aucune partition swap choisie. Le script va être terminé."
    ;;
    se)
    M1="Ingen swappartition vald. Skriptet avbryts."
    ;;
    *)
    M1="No swap partition chosen. The script will be terminated."
    ;;
    esac
    $DIA --backtitle "$BT" --title "$T1" --msgbox "$M1" 15 40
    rm -f $TMP
    exit 0
  fi
  case "$ORIG_LANGUAGE" in
  de|at|ch)
  M1="Die gewählte Partition ist kleiner als $SWAPMIN MB. Das Skript wird beendet."
  ;;
  es)
  M1="La partición swap seleccionada es menor que $SWAPMIN MB. El script finalizará."
  ;;
  fr)
  M1="La partition swap choisie est inférieure à $SWAPMIN MB. Le script va être terminé."
  ;;
  se)
  M1="Den valda swap partitionen är mindre än $SWAPMIN MB. Skriptet avbryts."
  ;;
  *)
  M1="The chosen swap partition is smaller than $SWAPMIN MB. The script will be terminated."
  ;;
  esac
  size=$(echo "$SWAPART" | grep "$SWCHOICE")
  size=${size%%_*}
  size=${size##* }
  if [ $size -lt $SWAPMIN ] ; then
    $DIA --backtitle "$BT" --title "$T1" --msgbox "$M1" 15 40
    rm -f $TMP
    exit 0
  fi
  case "$ORIG_LANGUAGE" in
  de|at|ch)
  M1="Soll $SWCHOICE als Swap eingerichtet werden (alle Daten auf der Partition gehen verloren)?"
  ;;
  es)
  M1="Quiere instalar $SWCHOICE como swap (se perderán todos los datos en esta partición)?"
  ;;
  fr)
  M1="Voulez-vous formater $SWCHOICE comme swap (toutes les données présentes sur cette partition seront perdues)?"
  ;;
  se)
  M1="Vill du använda $SWCHOICE som swap (alla data på denna partition raderas)?"
  ;;
  *)
  M1="Do you want to set up $SWCHOICE as swap (all data on this partition will be lost)?"
  ;;
  esac
  $DIA --backtitle "$BT" --title "$T1" --yesno "$M1" 15 60
  x=$?
  if [ $x != 0 ] ; then
    case "$ORIG_LANGUAGE" in
    de|at|ch)
    M1="Abgebrochen, das Skript wird beendet."
    ;;
    es)
    M1="Cancelado. El script finalizará."
    ;;
    fr)
    M1="Annulation. Le script va être terminé."
    ;;
    se)
    M1="Avbrutet. Skriptet avbryts."
    ;;
    *)
    M1="Cancelled. The script will be terminated."
    ;;
    esac
    $DIA --backtitle "$BT" --title "$T1" --msgbox "$M1" 15 40
    rm -f $TMP
    exit 0
  fi
  case "$ORIG_LANGUAGE" in
  de|at|ch)
  echo "Partition $SWCHOICE wird als Swap eingerichtet..."
  ;;
  es)
  echo "Instalando $SWCHOICE como swap..."
  ;;
  fr)
  echo "Formate $SWCHOICE comme swap..."
  ;;
  se)
  echo "Formaterar $SWCHOICE till swappartition..."
  ;;
  *)
  echo "Setting up $SWCHOICE as swap..."
  ;;
  esac
  sleep 2
  dd if=/dev/zero of=$SWCHOICE bs=1k count=16 >/dev/null 2>&1
  sync
  mkswap $SWCHOICE 2> $TMP
  if [ $? != 0 ] ; then
    case "$ORIG_LANGUAGE" in
    de|at|ch)
    M1="Beim Einrichten der Swap-Partition ist ein Fehler aufgetreten. Hier die Meldungen von mkswap:"
    ;;
    es)
    M1="Ocurrió un error mientras se instalaba la swap. Algunos mensajes de mkswap:"
    ;;
    fr)
    M1="Une erreur est intervenue pendant le formatage de la swap. Quelques messages de mkswap:"
    ;;
    se)
    M1="Fel vid formatering av swappartitionen. Meddelanden från mkswap:"
    ;;
    *)
    M1="An error occurred while setting up swap. Some messages from mkswap:"
    ;;
    esac
    $DIA --backtitle "$BT" --title "$T1" \
      --msgbox "$M1 `tail -8 $TMP`" 15 60
    rm -f $TMP
    exit 0
  fi
  swapon $SWCHOICE >/dev/null 2>&1
else
  SWCHOICE=none
fi

# select root partition (create filesystem)
> $TMP
fdisk -l /dev/$HDCHOICE | grep "^/dev.*Linux$" | tr -d '*' |
while read dev x x size x
do
  size=${size%+}
  echo $dev $[size/1024]_MB off >> $TMP
done
NUMEXT2="`wc -l <$TMP`"
EXT2PART="`cat $TMP`"
case "$ORIG_LANGUAGE" in
de|at|ch)
T1="Filesystem anlegen"
M1="Es wurde keine Linux-Partition auf der gewählten Platte gefunden. Das Skript wird beendet."
;;
es)
T1="Crear sistema de ficheros"
M1="No se pudo encontrar ninguna partición Linux en el disco duro seleccionado. El script finalizará."
;;
fr)
T1="Création du système de fichiers"
M1="Aucune partition Linux trouvée sur le disque dur sélectionné. Le script va être terminé."
;;
se)
T1="Formatera Linuxpartition"
M1="Kunde inte hitta en Linux partition på den valda hårddisken. Skriptet avbryts."
;;
*)
T1="Create filesystem"
M1="No Linux partition could be found on the chosen hard disk. The script will be terminated."
;;
esac
if [ $NUMEXT2 = 0 ] ; then
  $DIA --backtitle "$BT" --title "$T1" --msgbox "$M1" 15 40
  rm -f $TMP
  exit 0
fi
case "$ORIG_LANGUAGE" in
de|at|ch)
M1="Wählen Sie die Rootpartition aus:"
;;
es)
M1="Elija la partición raíz:"
;;
fr)
M1="Choisissez la partition root:"
;;
se)
M1="Välj partition till Linux (rootpartitionen):"
;;
*)
M1="Choose the root partition:"
;;
esac
$DIA --backtitle "$BT" --title "$T1" --radiolist "$M1" 16 60 $NUMEXT2 \
  $EXT2PART 2> $TMP
FSCHOICE="`cat $TMP`"
case "$ORIG_LANGUAGE" in
de|at|ch)
M1="Sie haben keine Partition ausgewählt. Das Skript wird beendet."
;;
es)
M1="No se ha seleccionado ninguna partición. El script finalizará."
;;
fr)
M1="Aucune partition choisie. Le script va être terminé."
;;
se)
M1="Ingen partition vald. Skriptet avbryts."
;;
*)
M1="No partition chosen. The script will be terminated."
;;
esac
if [ -z "$FSCHOICE" ] ; then
  $DIA --backtitle "$BT" --title "$T1" --msgbox "$M1" 15 40
  rm -f $TMP
  exit 0
fi
size=$(echo "$EXT2PART" | grep "$FSCHOICE")
size=${size%%_*}
size=${size##* }
case "$ORIG_LANGUAGE" in
de|at|ch)
M1="Die gewählte Partition ist kleiner als $FSMIN MB. Das Skript wird beendet."
;;
es)
M1="La partición seleccionada es menor que $FSMIN MB. El script finalizará."
;;
fr)
M1="La partition choisie est inférieure à $FSMIN MB. Le script va être terminé."
;;
se)
M1="Den valda partitionen är mindre än $FSMIN MB. Skriptet avbryts."
;;
*)
M1="The chosen partition is smaller than $FSMIN MB. The script will be terminated."
;;
esac
if [ $size -lt $FSMIN ] ; then
  $DIA --backtitle "$BT" --title "$T1" --msgbox "$M1" 15 40
  rm -f $TMP
  exit 0
fi

# select filesystem type
case "$ORIG_LANGUAGE" in
de|at|ch)
M1="Wählen Sie den Dateisystem-Typ aus:"
;;
fr)
M1="Choisissez le type de système de fichiers:"
;;
se)
M1="Välj filsystem (reiserfs är ett bra val):"
;;
*)
M1="Choose the filesystem type:"
;;
esac
FSLIST="ext2 second_extended off ext3 journal_extended off reiserfs reiser off xfs xfs off"
NUMFS=4
$DIA --backtitle "$BT" --title "$T1" --radiolist "$M1" 16 60 $NUMFS \
  $FSLIST 2> $TMP
FSTYPE="`cat $TMP`"
[ -z "$FSTYPE" ] && FSTYPE=ext2
case "$ORIG_LANGUAGE" in
de|at|ch)
M1="Soll auf $FSCHOICE das Filesystem erzeugt werden (alle Daten auf der Partition gehen verloren)?"
;;
es)
M1="Quiere crear un sistema de ficheros en $FSCHOICE (se perderán todos los datos en esta partición)?"
;;
fr)
M1="Voulez-vous créer un système de fichiers sur $FSCHOICE (toutes les données présentes sur cette partition seront perdues)?"
;;
se)
M1="Vill du formatera $FSCHOICE till Linux  partition. (Alla data på denna partition kommer raderas)?"
;;
*)
M1="Do you want to create a filesystem on $FSCHOICE (all data on this partition will be lost)?"
;;
esac
$DIA --backtitle "$BT" --title "$T1" --yesno "$M1" 15 60
x=$?
if [ $x != 0 ] ; then
  case "$ORIG_LANGUAGE" in
  de|at|ch)
  M1="Abgebrochen, das Skript wird beendet."
  ;;
  es)
  M1="Cancelado. El script finalizará."
  ;;
  fr)
  M1="Annulation. Le script va être terminé."
  ;;
  se)
  M1="Avbrutet. Skriptet avbryts."
  ;;
  *)
  M1="Cancelled. The script will be terminated."
  ;;
  esac
  $DIA --backtitle "$BT" --title "$T1" --msgbox "$M1" 15 40
  rm -f $TMP
  exit 0
fi
case "$ORIG_LANGUAGE" in
de|at|ch)
echo "Das Filesystem wird auf $FSCHOICE angelegt..."
;;
es)
echo "Creando el sistema de ficheros en $FSCHOICE..."
;;
fr)
echo "Créé le système de fichiers sur $FSCHOICE..."
;;
se)
echo "Formaterar Linuxpartitionen (rootpartitionen) $FSCHOICE..."
;;
*)
echo "Creating filesystem on $FSCHOICE..."
;;
esac
sleep 2
dd if=/dev/zero of=$FSCHOICE bs=1k count=16 >/dev/null 2>&1
sync
case $FSTYPE in
  xfs)
    mkfs.$FSTYPE -f $FSCHOICE 2> $TMP
    x=$?
  ;;
  reiserfs)
    echo y | mkfs.$FSTYPE $FSCHOICE 2> $TMP
    x=$?
  ;;
  *)
    mkfs.$FSTYPE $FSCHOICE 2> $TMP
    x=$?
    case $FSTYPE in *ext*) tune2fs -O ^dir_index $FSCHOICE;; esac
  ;;
esac
if [ $x != 0 ] ; then
  case "$ORIG_LANGUAGE" in
  de|at|ch)
  M1="Beim Anlegen des Filesystems ist ein Fehler aufgetreten. Hier die Meldungen von mkfs:"
  ;;
  es)
  M1="Ocurrió un error mientras se creaba el sistema de ficheros. Algunos mensajes de mkfs:"
  ;;
  fr)
  M1="Une erreur est intervenue pendant la création du système de fichiers. Quelques messages de mkswap:"
  ;;
  se)
  M1="Fel under formateringen. Meddelande från mkfs:"
  ;;
  *)
  M1="An error occurred while creating the filesystem. Some messages from mkfs:"
  ;;
  esac
  $DIA --backtitle "$BT" --title "$T1" --msgbox "$M1 `tail -8 $TMP`" 15 60
  rm -f $TMP
  exit 0
fi

case "$ORIG_LANGUAGE" in
de|at|ch)
T1="Dateien kopieren"
M1="Jetzt werden die Dateien der StreamBOX-CD auf die Rootpartition kopiert. Dies kann je nach Geschwindigkeit der Festplatte und des CDROM-Laufwerks 10-40 Minuten dauern."
M2="Kopiere Dateien..."
;;
es)
T1="Copiar archivos"
M1="Ahora se copiarán todos los archivos del CD de StreamBOX al disco duro. Esto lleverá de 10 a 40 minutos, dependiendo del hardware."
M2="Copiando archivos..."
;;
fr)
T1="Copier les fichiers"
M1="Copie maintenant tous les fichiers du CD sur le disque dur. Celà va prendre de 10 à 40 minutes, selon le matériel."
M2="Copie les fichiers..."
;;
se)
T1="Kopiera filerna"
M1="Kopierar nu alla filerna från StreamBOX CDn till hårddisken. Detta kommer ta 10 till 40 minuter beroende på datorn."
M2="Kopierar filer..."
;;
*)
T1="Copy files"
M1="Now copying all files from the StreamBOX CD to hard disk. This will take 10 to 40 minutes, depending on the hardware."
M2="Copying files..."
;;
esac
$DIA --backtitle "$BT" --title "$T1" --msgbox "$M1" 15 60

mkdir -p $TR >/dev/null 2>&1
mount -t $FSTYPE $FSCHOICE $TR 2> $TMP
if [ $? != 0 ] ; then
  case "$ORIG_LANGUAGE" in
  de|at|ch)
  M1="Beim Einbinden der Rootpartition $FSCHOICE ist ein Fehler aufgetreten. Hier die Meldungen von mount:"
  ;;
  es)
  M1="Ocurrió un error mientras se montaba la partición raíz $FSCHOICE. Algunos mensajes de mount:"
  ;;
  fr)
  M1="Une erreur est intervenue lors du montage de la partition root $FSCHOICE. Quelques messages de mount:"
  ;;
  se)
  M1="Fel vid montering av $FSCHOICE rootpartitionen. Meddelande från mount:"
  ;;
  *)
  M1="An error occurred while mounting the root partition $FSCHOICE. Some messages from mount:"
  ;;
  esac
  $DIA --backtitle "$BT" --title "$T1" --msgbox "$M1 `tail -8 $TMP`" 15 60
  rm -f $TMP
  exit 0
fi
# now the root filesystem is filled with data
echo -n "$M2"
(cd /KNOPPIX ; cp -a * $TR ; sync) &
progressbar $!
#rotdash $!
# two beeps
echo -ne "\007" >/dev/tty1 ; usleep 500000
echo -ne "\007" >/dev/tty1 ; usleep 500000
case "$ORIG_LANGUAGE" in
de|at|ch)
T1="Dateien kopiert"
M1="Der Kopiervorgang ist abgeschlossen."
;;
es)
T1="Copia finalizada"
M1="El proceso de copia ha finalizado."
;;
fr)
T1="Copie terminée"
M1="Le processus de copie des fichier est terminé."
;;
se)
T1="Kopieringen avslutad"
M1="Kopieringen är klar."
;;
*)
T1="Copying finished"
M1="The copying process has finished."
;;
esac
$DIA --backtitle "$BT" --title "$T1" --msgbox "$M1" 15 40

# extract templates
mkdir -p $TM
tar xpzf $INSTDATA -C $TM >/dev/null 2>&1

# "normalize" runlevel directories
rm -f $TR/etc/rc[023456S].d/*
for x in 0 5 6 S
do
  cp -a $TM/etc/rc$x.d/* $TR/etc/rc$x.d/
done
for x in 2 3 4
do
  cp -a $TM/etc/rc5.d/* $TR/etc/rc$x.d/
done

# select services to be started at boot time
case "$ORIG_LANGUAGE" in
de|at|ch)
T1="Mailserver"
M1="Soll der Mailserver (smail) beim Hochfahren des Systems gestartet werden?"
;;
es)
T1="Servidor de correo"
M1="Quiere ejecutar el servidor de correo (smail) al arrancar el sistema?"
;;
fr)
T1="Serveur de mail"
M1="Voulez-vous que le serveur de mail (smail) soit lancé au démarrage?"
;;
se)
T1="Mail server"
M1="Vill du starta mailservern (smail) när GNU/Linux startar?"
;;
*)
T1="Mail server"
M1="Do you want to start the mail server (smail) at system boot?"
;;
esac
$DIA --backtitle "$BT" --title "$T1" --yesno "$M1" 15 60
x=$?
if [ $x != 0 ] ; then
  rm -f $TR/etc/rc5.d/S??smail
fi
case "$ORIG_LANGUAGE" in
de|at|ch)
T1="Secure Shell Server"
M1="Soll der Secure Shell Server (sshd) beim Hochfahren des Systems gestartet werden?"
;;
es)
T1="Servidor de shell seguro"
M1="Quiere ejecutar el servidor de shell seguro (sshd) al arrancar el sistema?"
;;
fr)
T1="Serveur de shell sécurisé"
M1="Voulez-vous que le serveur de shell sécurisé (sshd) soit lancé au démarrage?"
;;
se)
T1="Secure shell server"
M1="Vill du starta Secure shell server (sshd) när GNU/Linux startar?"
;;
*)
T1="Secure shell server"
M1="Do you want to start the secure shell server (sshd) at system boot?"
;;
esac
$DIA --backtitle "$BT" --title "$T1" --yesno "$M1" 15 60
x=$?
if [ $x != 0 ] ; then
  rm -f $TR/etc/rc5.d/S??ssh
fi
case "$ORIG_LANGUAGE" in
de|at|ch)
T1="Samba Server"
M1="Soll der Samba Server (smbd/nmbd) beim Hochfahren des Systems gestartet werden?"
;;
es)
T1="Servidor Samba"
M1="Quiere ejecutar el servidor samba (smbd/nmbd) al arrancar el sistema?"
;;
fr)
T1="Serveur samba"
M1="Voulez-vous que le serveur samba (smbd/nmbd) soit lancé au démarrage?"
;;
se)
T1="Filservern Samba"
M1="Vill du starta filservern Samba (smbd/nmbd) när GNU/Linux startar?"
;;
*)
T1="Samba server"
M1="Do you want to start the samba server (smbd/nmbd) at system boot?"
;;
esac
$DIA --backtitle "$BT" --title "$T1" --yesno "$M1" 15 60
x=$?
if [ $x != 0 ] ; then
  rm -f $TR/etc/rc5.d/S??samba
fi
case "$ORIG_LANGUAGE" in
de|at|ch)
T1="Cups Server"
M1="Soll der Druckserver (cupsd) beim Hochfahren des Systems gestartet werden?"
;;
fr)
T1="Serveur d'impression"
M1="Voulez-vous que le serveur d'impression (cupsd) soit lancé au démarrage?"
;;
se)
T1="Skrivarserver"
M1="Vill du starta skrivarservern (cupsd) när GNU/Linux startar?"
;;
*)
T1="Cups server"
M1="Do you want to start the printing server (cupsd) at system boot?"
;;
esac
$DIA --backtitle "$BT" --title "$T1" --yesno "$M1" 15 60
x=$?
if [ $x != 0 ] ; then
  rm -f $TR/etc/rc5.d/S??cupsys
fi
case "$ORIG_LANGUAGE" in
de|at|ch)
T1="K Display Manager"
M1="Soll der K Display Manager (grafische Anmeldung) beim Hochfahren des Systems gestartet werden?"
;;
es)
T1="Gestor de pantalla de KDE"
M1="Quiere ejecutar kdm (ingreso en el sistema de forma gráfica) al arrancar el sistema?"
;;
fr)
T1="K display manager"
M1="Voulez-vous que le login graphique (kdm) soit lancé au démarrage?"
;;
se)
T1="kdm grafisk inloggning"
M1="Vill du starta kdm (grafisk inloggning) när GNU/Linux startar? (rekommenderas om grafiken fungerar)"
;;
*)
T1="K display manager"
M1="Do you want to start kdm (graphical login) at system boot?"
;;
esac
$DIA --backtitle "$BT" --title "$T1" --yesno "$M1" 15 60
x=$?
if [ $x != 0 ] ; then
  rm -f $TR/etc/rc5.d/S??kdm
fi
# remove hotplug if no USB module is loaded
grep -E "usb|uhci|ohci" /proc/modules >/dev/null 2>&1
if [ $? != 0 ] ; then
  rm -f $TR/etc/rc5.d/S??hotplug
fi
# remove cardmgr if no PCMCIA module is loaded
grep "pcmcia_core" /proc/modules >/dev/null 2>&1
if [ $? != 0 ] ; then
  rm -f $TR/etc/rc5.d/S??pcmcia
fi

# set keymap
case "$ORIG_LANGUAGE" in
de|at|ch)
cp -af $TM/etc/init.d/keymap.sh-de $TR/etc/init.d/keymap.sh
;;
es)
cp -af $TM/etc/init.d/keymap.sh-es $TR/etc/init.d/keymap.sh
;;
fr)
cp -af $TM/etc/init.d/keymap.sh-fr $TR/etc/init.d/keymap.sh
;;
# FIXME: create keymap.sh-se with
# /usr/share/keymaps/i386/qwerty/se-latin1.kmap.gz in templates
se)
cp -af $TM/etc/init.d/keymap.sh-se $TR/etc/init.d/keymap.sh
;;
*)
cp -af $TM/etc/init.d/keymap.sh-en $TR/etc/init.d/keymap.sh
;;
esac

# create device symlinks /dev/cdrom and /dev/mouse
if [ -f /etc/sysconfig/mouse ] ; then
  x="`grep DEVICE= /etc/sysconfig/mouse`"
  x=${x#*/dev/}
  MOUSEDEV=${x%\"*}
fi
[ -z "$MOUSEDEV" ] && MOUSEDEV="psaux"
(cd $TR/dev ; ln -sf $MOUSEDEV mouse ; ln -sf sr0 cdrom)

# change prompt and remove "." from PATH (/etc/profile)
cp -af $TM/etc/profile $TR/etc/profile

# "normalize" /etc/inittab
cp -af $TM/etc/inittab $TR/etc/inittab

# update /etc/motd
echo -e "Welcome to StreamBOX (Kernel `uname -r`)\n" > $TR/etc/motd

# create /etc/modules from current loaded modules
cat <<\EOF >$TMP
# /etc/modules: kernel modules to load at boot time.
#
# This file should contain the names of kernel modules that are
# to be loaded at boot time, one per line.  Comments begin with
# a `#', and everything on the line after them are ignored.
EOF
cat /proc/modules | tac | grep -v '\[.*\]' | grep -v cloop |
while read mod x
do
  if [ $mod = apm ] ; then
    echo "apm power_off=1" >>$TMP
  else
    echo $mod >>$TMP
  fi
done
cp -f $TMP $TR/etc/modules

# change /etc/inputrc to 8-bit clean input
cp -af $TM/etc/inputrc $TR/etc/inputrc

# create /etc/fstab
cat <<EOF >$TR/etc/fstab
# /etc/fstab: filesystem table.
#
# filesystem  mountpoint  type  options  dump  pass
EOF
case $FSTYPE in
  reiserfs|xfs)
  echo "$FSCHOICE  /  $FSTYPE  defaults  0  1" >>$TR/etc/fstab
  ;;
  *)
  echo "$FSCHOICE  /  $FSTYPE  defaults,errors=remount-ro  0  1" >>$TR/etc/fstab
  ;;
esac
if [ $SWCHOICE != none ] ; then
  echo "$SWCHOICE  none  swap  sw  0  0" >>$TR/etc/fstab
fi
cat <<EOF >>$TR/etc/fstab
proc  /proc  proc  defaults  0  0
/dev/fd0  /floppy  vfat  defaults,user,noauto,showexec,umask=022  0  0
EOF

# Add CD-Roms/DVD/...
# Symlinks + Mountpoints

for i in /dev/cdrom* /dev/dvd /dev/cdaudio
do
  [ -L $i ] || continue
  echo "$i /${i/\/dev\//}  iso9660  defaults,ro,user,noexec,noauto  0  0" >> $TR/etc/fstab
  mkdir -p $TR/${i/\/dev\//}
  readlink $i | grep -q "KNOPPIX" || cp -a $i $TR/dev/
done

# Let Knoppix detect all other partitions
chroot "$TR" mount /proc
chroot "$TR" rebuildfstab -r
chroot "$TR" umount /proc

# add DMA activation to bootmisc.sh (commented out if nodma is set)
# new dma-mode from new knoppix-code
x="#"
checkbootparam dma && x=''
echo "# enable DMA" >>$TR/etc/init.d/bootmisc.sh
if [ -f /proc/partitions ] ; then
  while read x x x p x
  do
    case "$p" in
      hd?)
        if [ -r "/proc/ide/$p/media" ] ; then
          echo "$x /sbin/hdparm -qd1 /dev/$p" >>$TR/etc/init.d/bootmisc.sh
        fi
        ;;
      *) ;;
    esac
  done < /proc/partitions
fi

# use Knoppix-generated XF86Config
cp -af /etc/X11/XF86Config $TR/etc/X11/XF86Config
cp -af /etc/X11/XF86Config-4 $TR/etc/X11/XF86Config-4

# backup Knoppix specific Xsession file
mv $TR/etc/X11/Xsession.d/45xsession $TR/root/xsession.knx-hdinstall.backup

# fix display permissions for xdm/kdm (bug in woody?)
sed -e 's,DisplayManager\*authorize:.*true,DisplayManager*authorize: false,g' /etc/X11/xdm/xdm-config >$TR/etc/X11/xdm/xdm-config
for x in /etc/kde[23]/kdm/kdmrc
do
  sed -e 's,#Authorize=false,Authorize=false,g' $x >$TR/$x
done

# set hostname
case "$ORIG_LANGUAGE" in
de|at|ch)
T1="Rechnernamen setzen"
M1="Geben Sie den Rechnernamen ein (ohne Domain-Anhang):"
;;
es)
T1="Asignar nombre de host"
M1="Dé un nombre de host a esta máquina (sin el dominio añadido):"
;;
fr)
T1="Nom de la machine"
M1="Saisissez un nom pour cette machine (sans le domaine):"
;;
se)
T1="Datorns namn (host)"
M1="Ge datorn ett namn (hostname), (utan domain):"
;;
*)
T1="Set hostname"
M1="Give a host name for this machine (without domain appended):"
;;
esac
$DIA --backtitle "$BT" --title "$T1" --inputbox "$M1" 15 60 $DEFHNAME 2>$TMP
HNAME="`cat $TMP`"
[ -z "$HNAME" ] && HNAME=$DEFHNAME
cat <<EOF >$TR/etc/hosts
127.0.0.1	$HNAME localhost

# The following lines are desirable for IPv6 capable hosts
# (added automatically by netbase upgrade)

::1     ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
ff02::3 ip6-allhosts
EOF
echo "$HNAME" > $TR/etc/hostname
echo "$HNAME" > $TR/etc/mailname

# set up ethernet (if present)
grep eth0 /proc/net/dev >/dev/null 2>&1
if [ $? = 0 ] ; then
  (
  LANG="$ORIG_LANG"
  LANGUAGE="$ORIG_LANGUAGE"
  LC_ALL="$ORIG_LC_ALL"
  rm -f /etc/resolv.conf
  touch /etc/resolv.conf
  netcardconfig
  )
  cp -af /etc/network/interfaces $TR/etc/network/interfaces
  : >$TR/etc/network/ifstate
  rm -f $TR/etc/resolv.conf
  cat /etc/resolv.conf >$TR/etc/resolv.conf
fi

# disable all services in /etc/inetd.conf
cp -af $TM/etc/inetd.conf $TR/etc/inetd.conf

# remove Knoppix entry from /etc/sudoers
cp -af $TM/etc/sudoers $TR/etc/sudoers

# remove Knoppix specific menu entries (they won't work without
# sudoers entry)
#chroot "$TR" rm -rf /usr/share/applnk/Knoppix /usr/share/gnome/apps/Knoppix
function suknoppixmenus
{
  [ "$#" -lt "2" ] && return 1

  supath=$1
  suprog=$2
  TMPDIR="/tmp/suknxmenu.$$"
  mkdir -p $TMPDIR

  cp -a $supath/* $TMPDIR
  cd $TMPDIR
  for i in $(find . -name "*.desktop")
  do
    sed 's/Exec=/Exec='$suprog' \-\- /g' $i > $supath/$i
  done

  # Cleanup
  rm -rf $TMPDIR
}

suknoppixmenus $TR/usr/share/applnk/StreamBOX kdesu
suknoppixmenus $TR/usr/share/gnome/apps/Knoppix gksu

# apt-get -q -y --purge remove cupsconfig-knoppix \
# chroot "$TR" apt-get -q -y --purge remove cupsconfig-knoppix \
# knoppix-terminalserver mkdosswapfile-knoppix netcardconfig-knoppix \
# rootshell-knoppix saveconfig-knoppix soundcardconfig-knoppix \
# sshstart-knoppix startnessus-knoppix wlcardconfig-knoppix \
# networkconfig-knoppix

# use Knoppix generated /etc/sysconfig/i18n file
mkdir -p $TR/etc/sysconfig
cp -af /etc/sysconfig/i18n $TR/etc/sysconfig/

# set OpenOffice language
mkdir -p $TR/etc/alternatives
rm -f $TR/etc/alternatives/soffice.*
cp -af /etc/alternatives/soffice.* $TR/etc/alternatives/

# use less restrictive /etc/hosts.allow
cp -af $TM/etc/hosts.allow $TR/etc/hosts.allow

# create "real" /tmp with mode 1777
rm -rf $TR/tmp
mkdir $TR/tmp
chmod 1777 $TR/tmp

# create /etc/mtab as a regular file
rm -f $TR/etc/mtab
touch $TR/etc/mtab

# change home directory of root to /root
sed -e 's,/home/root,/root,g' /etc/passwd > $TR/etc/passwd

# create home directory for user streambox
rm -rf $TR/home/streambox
cp -a $TR/etc/skel $TR/home
mv $TR/home/skel $TR/home/streambox
chown -R streambox.streambox $TR/home/streambox

chroot "$TR" su streambox -c mkdesktophdicons

# force kde first time configuration
if [ -f /etc/skel/.kde/share/config/kpersonalizerrc ] ; then
  sed -e 's/FirstLogin=false/FirstLogin=true/g' \
  /etc/skel/.kde/share/config/kpersonalizerrc > $TMP
  cp -f $TMP $TR/etc/skel/.kde/share/config/kpersonalizerrc
  cp -f $TMP $TR/home/streambox/.kde/share/config/kpersonalizerrc
fi

getpassword(){
HEADER="$1"
ENTER="$2"
AGAIN="$3"
PASS1=""
PASS2=""
until [ -n "$PASS1" -a "$PASS1" = "$PASS2" ]; do
rm -f "$TMP.pass"
if [ "$DIA" = "Xdialog" ]; then
Xdialog --title "$BT" --password --password --2inputsbox "$HEADER" 15 60 "$ENTER" "" "$AGAIN" "" 2>"$TMP.pass"
PASSWORDS="$(<$TMP.pass)"
PASS1="${PASSWORDS%%/*}"
PASS2="${PASSWORDS##*/}"
else
$DIA --backtitle "$BT" --title "$HEADER" --passwordbox "$ENTER" 8 65 "" 2>"$TMP.pass"
PASS1="$(<$TMP.pass)"
$DIA --backtitle "$BT" --title "$HEADER" --passwordbox "$AGAIN" 8 65 "" 2>"$TMP.pass"
PASS2="$(<$TMP.pass)"
fi
done
rm -f "$TMP.pass"
echo "$PASS1" >&2
}

# set passwords for users root and knoppix using chroot
case "$ORIG_LANGUAGE" in
de|at|ch)
T1="Root-Passwort setzen"
M1="Neues Passwort für den User root setzen (wird nicht angezeigt):"
M2="Neues Passwort für den User root setzen (nochmal zur Kontrolle):"
;;
es)
T1="Set root password"
M1="Asigne una nueva contraseña para el usuario root"
M2="$M1"
;;
fr)
T1="Set root password"
M1="Saisissez un nouveau mot de passe pour l'utilisateur root"
M2="$M1"
;;
se)
T1="Set root password"
M1="Skriv nytt password för root (=System Administrator)."
M2="$M1"
;;
*)
T1="Set root password"
M1="Set new password for user root (input is not displayed):"
M2="Set new password for user root (again to prevent typos):"
;;
esac

getpassword "$T1" "$M1" "$M2" 2>"$TMP"
PASS="$(<$TMP)"
chroot $TR sh -c "echo \"root:$PASS1\" | chpasswd"

case "$ORIG_LANGUAGE" in
de|at|ch)
T1="Passwort setzen"
M1="Neues Passwort für den User streambox setzen (wird nicht angezeigt):"
M2="Neues Passwort für den User streambox setzen (nochmal zur Kontrolle):"
;;
es)
T1="Set password"
M1="Asigne una nueva contraseña para el usuario streambox"
M2="$M1"
;;
fr)
T1="Set password"
M1="Saisissez un nouveau mot de passe pour l'utilisateur streambox"
M2="$M1"
;;
se)
T1="Set password"
M1="Skriv nytt password för användaren streambox"
M2="$M1"
;;
*)
T1="Set password"
M1="Set new password for user streambox (input is not displayed):"
M2="Set new password for user streambox (again to prevent typos):"
;;
esac

getpassword "$T1" "$M1" "$M2" 2>"$TMP"
PASS="$(<$TMP)"
chroot $TR sh -c "echo \"streambox:$PASS1\" | chpasswd"

INITRD=""
INITMODS=""
mkdir -p $TL1 $TL2 >/dev/null 2>&1
# loop-mount Knoppix bootfloppy
mount -t vfat -o loop,ro /cdrom/KNOPPIX/boot.img $TL1
gzip -cd $TL1/miniroot.gz > $TR/miniroot
umount $TL1
# loop-mount Knoppix miniroot
mount -t ext2 -o loop,ro $TR/miniroot $TL1

# if installing to SCSI disk: copy modules to initrd
case "$FSCHOICE" in
  /dev/sd*)
    # only SCSI modules contained on the bootfloppy
    for i in `ls $TL1/modules/scsi`
    do
      i=${i%.o}
      if [ -n "`grep $i /proc/modules`" ] ; then
        INITMODS="$INITMODS $i"
      fi
    done
    ;;
  *)
    ;;
esac
# if FSTYPE is ext3, reiserfs: copy modules to initrd
case "$FSTYPE" in
  ext3)
    INITMODS="$INITMODS jbd ext3"
    PIVOTFS="ext3"
    ;;
  reiserfs)
    INITMODS="$INITMODS reiserfs"
    ;;
  xfs)
    INITMODS="$INITMODS xfs"
    ;;
  *)
    ;;
esac
# create initrd if INITMODS is not empty
if [ -n "$INITMODS" ] ; then
  dd if=/dev/zero of=$TR/ird bs=1k count=$INSIZE
  mke2fs -F -m 0 -i 1024 -q $TR/ird
  # loop-mount new initrd
  mount -t ext2 -o loop,rw $TR/ird $TL2
  cp -a $TL1/dev $TL1/etc $TL1/static $TL2
  mkdir -p $TL2/proc $TL2/modules $TL2/lib $TL2/mnt
  echo "#!/static/sh" >$TL2/linuxrc
  for i in $INITMODS
  do
    cp $(modinfo $i | grep "^filename:" | cut -d":" -f 2) $TL2/modules
    echo "insmod /modules/$i.o" >>$TL2/linuxrc
  done
  if [ -n "$PIVOTFS" ] ; then
    # copy mini pivot_root from templates
    cp -a $TM/etc/knx_pivot_root $TL2/static/pivot_root
    mkdir -p $TR/initrd
    echo "mount -t proc proc /proc" >>$TL2/linuxrc
    echo "echo 256 > /proc/sys/kernel/real-root-dev" >>$TL2/linuxrc
    echo "umount /proc" >>$TL2/linuxrc
    echo "mount -t $PIVOTFS $FSCHOICE /mnt" >>$TL2/linuxrc
    echo "/static/pivot_root /mnt /mnt/initrd" >>$TL2/linuxrc
  fi
  chmod 755 $TL2/linuxrc
  umount $TL1
  umount $TL2
  rm -rf $TR/miniroot
  gzip -9 $TR/ird
  mv $TR/ird.gz $TR/boot/initrd.gz
  INITRD="	initrd=/boot/initrd.gz"
else
  umount $TL1
fi

# set up LILO in chroot environment
case "$ORIG_LANGUAGE" in
de|at|ch)
T1="Bootloader einrichten"
M1="Soll der Bootloader (LILO) in den Master Boot Record (MBR) geschrieben werden?"
;;
es)
T1="Instalar cargador de arranque"
M1="Quiere instalar el cargador de arranque (LILO) en el master boot record (MBR)?"
;;
fr)
T1="Mise en place du chargeur de démarrage"
M1="Voulez-vous installer le chargeur de démarrage (LILO) dans le master boot record (MBR)?"
;;
se)
T1="Installation av LILO, en boot manager"
M1="Vill du installera bootmanagern (LILO) i MBR dvs. i början av första hårddisken (viss risk att data raderas)?"
;;
*)
T1="Set up boot loader"
M1="Do you want to install the boot loader (LILO) into the master boot record (MBR)?"
;;
esac
$DIA --backtitle "$BT" --title "$T1" --yesno "$M1" 15 60
x=$?
if [ $x = 0 ] ; then
  if stringinstring "hd[a-d]" "$FSCHOICE"
  then
    LBOOT=${FSCHOICE%%?[1-9]*}a # Set MBR to /dev/hda
  else
    LBOOT=${FSCHOICE%%[1-9]*}
  fi
  # Make a backup of the old mbr
  dd if=$LBOOT of=$TR/boot/knoppix-old-mbr.$(date +"%s") bs=512 count=1
else
  LBOOT=$FSCHOICE
fi
BKERNEL="/boot/vmlinuz-`uname -r`"
[ ! -e "$TR/vmlinuz" ] && ln -sf "$BKERNEL" "$TR/vmlinuz"

rm -f $TR/etc/lilo.conf

# extract vga mode from CMDLINE
VGAMODE=`getbootparam vga`
[ -z "$VGAMODE" ] && VGAMODE="$DEFVGA"

# use genliloconf if present
if ! ( echo -ne "vga=$VGAMODE\n" ; /usr/sbin/genliloconf "$LBOOT" "$FSCHOICE" "hda=scsi hdb=scsi hdc=scsi hdd=scsi hde=scsi hdf=scsi hdg=scsi hdh=scsi apm=power-off nomce" "$BKERNEL" $INITRD ) >$TR/etc/lilo.conf ; then
  cat <<EOF >$TR/etc/lilo.conf
boot=$LBOOT
vga=$VGAMODE
prompt
timeout=50
append = "hda=scsi hdb=scsi hdc=scsi hdd=scsi hde=scsi hdf=scsi hdg=scsi hdh=scsi apm=power-off nomce"

image=$BKERNEL
	label=streambox
	root=$FSCHOICE
	read-only
$INITRD

## A Windows installation, example for partition 1 on first IDE harddisk
# other=/dev/hda1
#	label=dos
#	optional
#	table=/dev/hda
EOF

fi

case "$ORIG_LANGUAGE" in
de|at|ch)
echo "Der Bootloader (LILO) wird eingerichtet..."
;;
es)
echo "Instalando el cargador de arranque (LILO)..."
;;
fr)
echo "Met en place le chargeur de démarrage (LILO)..."
;;
se)
echo "Installerar bootmanager (LILO)..."
;;
*)
echo "Setting up boot loader (LILO)..."
;;
esac
lilo -r $TR
# copy LILO bootsector to a file (for boot.ini in NT/2k/XP)
if [ $LBOOT = $FSCHOICE ] ; then
  dd if=$LBOOT of=$TR/linboot.img bs=512 count=1
fi

# size of boot floppy
FLSIZE=1423
KSIZE=`ls -s --block-size=1024 $BKERNEL`
KSIZE=${KSIZE%%/*}
if [ -n "$INITRD" ] ; then
  RDSIZE=`ls -s --block-size=1024 $TR/boot/initrd.gz`
  RDSIZE=${RDSIZE%%/*}
else
  RDSIZE=0
fi
# add 10 kilobytes for bootloader and check size
x=0
if [ $[KSIZE+RDSIZE+10] -ge $FLSIZE ] ; then
  case "$ORIG_LANGUAGE" in
  de|at|ch)
  T1="Hinweis"
  M1="Eine Bootdiskette kann nicht erzeugt werden, weil Kernel und Ramdisk zu groß sind."
  ;;
  fr)
  T1="Ooops!"
  M1="Créare un disquete de démarrage ne pas possiblé..."
  ;;
  se)
  T1="Oj Oj!"
  M1="Kan inte skapa en start diskett, kärnan och ramdisk är tyvärr för stora."
  ;;
  *)
  T1="Hint"
  M1="Can't create boot floppy, because kernel and ramdisk are too big."
  ;;
  esac
  $DIA --backtitle "$BT" --title "$T1" --msgbox "$M1" 15 40
  x=1
fi
# create boot floppy
if [ $x = 0 ] ; then
  case "$ORIG_LANGUAGE" in
  de|at|ch)
  T1="Bootdiskette erzeugen"
  M1="Soll eine Bootdiskette erzeugt werden (empfohlen)?"
  ;;
  es)
  T1="Crear disquete de arranque"
  M1="Quiere crear un disquete de arranque (recomendado) ?"
  ;;
  fr)
  T1="Disquette de démarrage"
  M1="Voulez-vous créer une disquette de démarrage (recommandé)?"
  ;;
  se)
  T1="Start (boot) diskett"
  M1="Vill du skapa en start (boot) diskett (rekommenderas)?"
  ;;
  *)
  T1="Create boot floppy"
  M1="Do you want to create a boot floppy (recommended)?"
  ;;
  esac
  $DIA --backtitle "$BT" --title "$T1" --yesno "$M1" 15 60
  x=$?
fi
if [ $x = 0 ] ; then
  case "$ORIG_LANGUAGE" in
  de|at|ch)
  M1="Legen Sie eine Diskette ein (alle Daten darauf gehen verloren)."
  M2="Schreibe Bootdiskette..."
  ;;
  es)
  M1="Inserte un disquete en la unidad /dev/fd0 (se perderán todos los datos en él)."
  M2="Escribiendo disquete de arranque..."
  ;;
  fr)
  M1="Insérer une disquette dans le lecteur /dev/fd0 (toutes les données présentes sur la disquette seront perdues)."
  M2="Ecriture de la disquette de démarrage..."
  ;;
  se)
  M1="Sätt in en diskett i datorn (i floppyn, alla data på disketten kommer raderas)."
  M2="Skriver startdiskett..."
  ;;
  *)
  M1="Insert a floppy in drive /dev/fd0 (all data on it will be lost)."
  M2="Writing boot floppy..."
  ;;
  esac
  $DIA --backtitle "$BT" --title "$T1" --msgbox "$M1" 15 40
  echo "$M2"
  mformat -t 80 -h 2 -s 18 a:
  syslinux /dev/fd0
  mount -t vfat /dev/fd0 $TL1
  cp $BKERNEL $TL1/vmlinuz
  [ -n "$INITRD" ] && cp $TR/boot/initrd.gz $TL1
cat <<EOF >$TL1/syslinux.cfg
default streambox
prompt 1
timeout 50
label streambox
  kernel vmlinuz
EOF
  echo -n "  append root=$FSCHOICE ro vga=$VGAMODE apm=power-off hda=scsi hdb=scsi hdc=scsi hdd=scsi hde=scsi hdf=scsi hdg=scsi hdh=scsi nomce" >>$TL1/syslinux.cfg
  if [ -n "$INITRD" ] ; then
    echo " initrd=initrd.gz" >>$TL1/syslinux.cfg
  else
    echo "" >>$TL1/syslinux.cfg
  fi
  [ $LBOOT = $FSCHOICE ] && cp $TR/linboot.img $TL1
  umount $TL1
fi

#echo -n "debug delay... "
#read x

# remove templates
rm -rf $TM
# detach all loop devices (otherwise $FSCHOICE will be busy)
for i in 7 6 5 4 3 2 1 0
do
  losetup -d /dev/loop$i >/dev/null 2>&1
done
# unmount root partition
umount $TR >/dev/null 2>&1

case "$ORIG_LANGUAGE" in
de|at|ch)
T1="Beendet"
M1="Die Installation ist abgeschlossen."
;;
es)
T1="Finalizado"
M1="El proceso de instalación ha terminado."
;;
fr)
T1="Terminée"
M1="L'installation est terminée."
;;
se)
T1="Klart"
M1="Installationen är klar."
;;
*)
T1="Finished"
M1="The installation process is finished."
;;
esac
$DIA --backtitle "$BT" --title "$T1" --msgbox "$M1" 15 40
rm -f $TMP
exit 0
