#!/bin/bash
appname=`basename "$0"`
ver="0.3.5a.2003041017"
copy="2002, 2003"
mail="PointedEars@gmx.de"
mail_feedback="bug-mozilla@PointedEars.de"
# ----------------------------------------------------------------------------
#     Mozilla Setup Wizard for GNU/Linux 0.3.5a
#     Copyright (c) 2002, 2003  Thomas Lahn <PointedEars@gmx.de>
#
#     This program is free software; you can redistribute it and/or modify
#     it under the terms of the GNU General Public License as published by
#     the Free Software Foundation; either version 2 of the License, or
#     (at your option) any later version.
#
#     This program is distributed in the hope that it will be useful,
#     but WITHOUT ANY WARRANTY; without even the implied warranty of
#     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#     GNU General Public License for more details.
#
#     You should have received a copy of the GNU General Public License
#     along with this program (COPYING file); if not, write to the
#     Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#
#     This is work in progress.
#     Send suggestions and bug reports to <bug-mozilla@PointedEars.de>
#
# ChangeLog
# ==========
#
# 0.3.5a (future)
# ----------------
#
# Enhancements:
#
# * Basic setup
#   - Show build type and ID before install
#   - Show $installer and `rm' output (incl. stderr) after "done"/"failed"
#   - Show free disk space on /tmp before asking for clean-up, uses -h option
#     if supported
# * XUL applications setup
#   - Uninstall as described under
#     http://white.sakura.ne.jp/~piro/xul/doc/installation.html.en#uninstall;
#   - Install all apps that match the Netscape installer quasi-standard
#     (-f && -x $archive/$installer/$installer)
#   - Added general `chmod go+r' in chrome/ to prevent later permission bugs
#     with XUL apps (such as `mozgest')
# * Allow repair of an existing installation, removing XUL cache file
# * Approaching POSIX conformance: Order of options does not matter any longer
# * Cosmetics
#   - Removed unused code (previously imported completely
#     from /etc/rc.status)
#   - Reversed exit codes (255 --> 1, 254 --> 2, ...)
#   - Use MozKill and isMozRunning funct's from the
#     Mozilla Process Manager (moz), version 0.2.2b+
#     (by this h4><OR)
#   - Complete ChangeLog in plain text file
#   - Faster output with multi-line `echo`s
#   - Output is preformatted for 80 cols;
#     reformats only when $COLUMNS is different (fast!)
#   - Reformatted source not to exceed 80 cols per line
#     (with `\' and/or LF) to make it easier legible on
#     the console
#   - Workaround kate's imperfect color coding with a bunch of `# `'
#     (post complains at kate.kde.org)
#
# Bugfixes:
#
# * XUL applications setup
#   - Removed duplicate status message ("not found")
#   - Fixed bug caused by "wrong" `pwd' when using the installer
#   - Fixed `$installler' typo in clean-up
# * Cosmetics
#   - s/Protected/Distributed/
#   - Use case...esac instead of if...elif...else whereever possible
#
# See the ChangeLog text file for further information.
#
#
# TO DO:
#
# * Basic setup:
#   - Working directory is current directory, not script directory
#   - Accept installer binary and skip extraction
# * POSIX conform parsing of options and arguments (incomplete)
# * Plugin import
#   - Allow overwrite
#   - Allow import of libnullplugin.so if desired
# * XUL applications setup
#   - If an application is about to be reinstalled (even as newer version),
#     it is automagically uninstalled first
#   - Allow to install second and following XPIs in an existing Mozilla session
#     (see MozKill below)
#   - `-M', `-B': Support other programs similar to Mozilla like Phoenix
#     (see moz 0.2.2RC1)
#   - Improve uninstaller:
#     1. [x] Terminate/kill mozilla-bin
#     2. [x] Edit chrome/installedchrome.txt
#     3. [x] Delete chrome/chrome.rdf and chrome/overlayinfo
#     4. [_] Delete ~/.mozilla/....slt/XUL.mf(as)l and
#            ~/.mozilla/....slt/chrome/chrome.rdf
# * Allow repair of an existing installation, removing cache files by priority
# * L10n: English and German (incomplete)
# * Optimize portability: Does this require `bash' or would `sh' suffice?
#   (to be tested on IRIX 6.5)
# * `-D', `--download':
#   Define the resource from where to download the gzipped tarball first
#   (use wget). The file is downloaded to the location specified by SOURCE.
# * `-T', `--truetype':
#   Modifies /usr/local/mozilla/defaults/pref/unix.js to use FreeType2 for
#   TrueType fonts. The directory /usr/X11R6/lib/X11/fonts/truetype is then
#   used by default, other font directories must be specified with the
#   `pref("font.directory.truetype.X", )' statement in unix.js or the
#   `user_pref(...)' statement in ~/.mozilla/...slt/unix.js
# * `-C', `--clean-up':
#   Removes the previously extracted mozilla installer directory
# * Cosmetics:
#   - More modular code (incomplete)
#   - Use parameter expansion whereever possible, like ${foo:-bar} and
#     ${#array} (incomplete)
#
# ----------------------------------------------------------------------------

function L {
  case $lg in
    de) echo "${2:-$1}";;
     *) echo "$1";;
  esac
}

function help {
  echo -n "
${extd}${appname}${norm}
  [${extd}-?${norm}] [${extd}-v${norm}] \
[${extd}-L${norm} LOCALE] [${extd}-I${norm} INSTALLER] [${extd}-U${norm} \
[USER]] [${extd}-R${norm}] [${extd}-D${norm} RESOURCE]
  [( ${extd}-c${norm} | ${extd}-s${norm} | ${extd}-h${norm} ) SOURCE \
[PLUGIN_DIR] [...] [${extd}-0o${norm}]]
  [${extd}-f${norm} [PLUGIN_DIR] [INST_PATH] [TGZ_PATH]]
  [( ${extd}-i${norm} | ${extd}-u${norm} ) [APP_NAME] [...]] [${extd}-d${norm} [MOZ_DIR]]
  SOURCE [TARGET]

  ${extd}-h${norm}, ${extd}--help${norm}         "
  L "Show this help and exit." \
    "Diese Hilfe anzeigen." | $fold
  echo -n "  ${extd}-v${norm}, ${extd}--verbose${norm}      "; \
  L "Activate verbose mode." \
    "Ausführliche Anzeige." | $fold
  echo -n "  ${extd}-L${norm}, ${extd}--locale${norm}       "
  L "Preselects the locale for program output." \
    "Wählt die Ausgabesprache." | $fold
  echo -n "    LOCALE             "
  L "A string of the form \`lc'[\`_CC'[\`.CHARSET']],
                       where \`lc' is a lowercased language code, \`CC' an
                       uppercased country code and \`CHARSET' a character
                       set code. While \`CC' and \`CHARSET' are optional
                       (note the rectangle brackets), a language code must
                       be provided, e.g. \`en', \`en_US' and \
\`en_US.US-ASCII'." \
    "Eine Zeichenfolge der Form \`lc'[\`_CC'[\`.CHARSET']],
                       wobei \`lc' ein Sprachcode in Kleinbuchstaben, \`CC'
                       ein Ländercode in Grossbuchstaben und \`CHARSET' ein
                       Zeichensatz ist. Während \`CC' und \`CHARSET' optional
                       sind (siehe die eckigen Klammern), ist ein Sprachcode
                       erforderlich, z.B. \`de', \`de_DE' und \
\`de_DE.ISO-8859-1'." | $fmt
  L "\
                       This program currently supports the English (\`en')
                       and German (\`de') locale. If you are not using the
                       \`-L' option, be sure to have your \`LANG' and/or
                       \`LC_CTYPE' environment properly set." \
    "\
                       Dieses Programm unterstützt zur Zeit Englisch
                       (\`en') und Deutsch (\`de') . Wenn Sie die Option
                       \`-L' nicht angeben, stellen Sie sicher, dass die
                       Umgebungsvariable(n) \`LANG' und/oder \`LC_CTYPE'
                       korrekt gesetzt sind." | $fmt
  echo -n "
${extd}`L "BASIC SETUP" \
          "BASIS-INSTALLATION"`${norm}

${extd}${appname}${norm}
  [...] [${extd}-I${norm} INSTALLER] [${extd}-U${norm} [USER]] \
[${extd}-R${norm}] [${extd}-D${norm} RESOURCE] SOURCE [TARGET] [...]

  ${extd}-I${norm}, ${extd}--installer${norm}    "
L "Use the installer program specified by INSTALLER." \
  "INSTALLER als Installationsprogramm verwenden." | $fold
  echo -n "    INSTALLER          "
  L "The default is \`mozilla-installer'. The program must" \
    "Standard ist \`mozilla-installer'. Das Programm" | $fold
  L "\
                       be contained in a directory with the same name. So if
                       you want to install Netscape instead of Mozilla, use
                       \`netscape-installer' as it is contained in the
                       \`netscape-installer' subdirectory." \
    "\
                       muss sich in einem Verzeichnis mit dem gleichen
                       Namen befinden. Wenn Sie also Netscape anstelle
                       von Mozilla installieren möchten, geben Sie
                       \`netscape-installer' an, weil dieser sich im
                       Unterverzeichnis \`netscape-installer' \
befindet." | $fmt
  echo -n "  ${extd}-U${norm}, ${extd}--user${norm}         "
L "Do a single-user install. The default is to do a" \
  "Installation nur für einen Benutzer durchführen." | $fold
  L "\
                       multi-user install which requires this program
                       to be run as \`root' (NOT \`su[do] root'!)." \
    "\
                       Ohne diese Angabe wird die Installation für alle
                       Benutzer durchgeführt, was es erforderlich macht,
                       dieses Programm als \`root' (NICHT \`su[do] root'!)
                       auszuführen." | $fmt
  L "\
                       If this option is provided in conjunction with \`-R'
                       (see below), the repair applies only to the files
                       of one user, otherwise to the files of all users." \
    "\
                       Wenn diese Option zusammen mit \`-R' (siehe unten)
                       verwendet wird, so wird die Reparatur nur für einen
                       Benutzer durchgeführt, anderenfalls für alle \
Benutzer." | $fmt
  L "                       ${extd}For future use.${norm}" \
    "                       ${extd}Für zukünftige Verwendung.${norm}" | $fmt
  echo -n "    USER               "
L "The name of the user whose installation should be" \
  "Name des Benutzers, für den installiert oder dessen" | $fold
  L "\
                       done or repaired. If left out, everything applies
                       to the current user (who ran the program)." \
    "\
                       Installation repariert werden soll. Wird dieses
                       Argument ausgelassen, so betreffen alle Aktionen
                       den aktuellen Benutzer (derjenige, welcher das
                       Programm gestartet hat)." | $fmt
  echo -n "  ${extd}-R${norm}, ${extd}--repair${norm}       "
L "Terminate all Mozilla processes and remove the files" \
  "Beenden aller Mozilla-Prozesse und entfernen der" | $fold
  L "\
                       XUL.mfasl, chrome/chrome.rdf and localstore.rdf from
                       the profile directories to rebuild them on next Mozilla
                       startup. (Write permission is required!)
                       As discussed in the newsgroup de.comm.software.mozilla
                       and on http://www.hmetzger.de/pdl.html, invalid data in
                       these files cause Mozilla malfunctions in many cases.
                       You may need to re-select the theme after repair." \
    "\
                       Dateien XUL.mf*l (XUL-Cache), chrome/chrome.rdf
                       (Themes-Einstellungen) und localstore.rdf
                       (Fenster-Einstellungen) aus den Profilverzeichnissen,
                       damit sie beim nächsten Mozilla-Start neu erstellt
                       werden. (Schreibrechte erforderlich!) 
                       Wie in der Newsgroup de.comm.software.mozilla und
                       auf http://www.hmetzger.de/Profilverzeichnisse.html
                       diskutiert, verursachen ungültige Daten in diesen
                       Dateien in vielen Fällen Mozilla-Fehlfunktionen.
                       Möglicherweise ist es erforderlich, das Theme nach
                       der Reparatur neu auszuwählen." | $fmt
  L "\
                       Use with CAUTION as \`root'! If SIGTERM(15) does
                       not work, SIGKILL(9) is sent and users will lose
                       all their unsaved data." \
    "\
                       VORSICHT bei der Verwendung als \`root'! Wenn
                       SIGTERM(15) nicht funktioniert, wird SIGKILL(9)
                       gesendet und Benutzer werden nicht gespeicherte
                       Daten verlieren!" | $fmt
  echo -n "  ${extd}-D${norm}, ${extd}--download${norm}     "
L "Download \`mozilla-installer' archive from" \
  "Archiv mit \`mozilla-installer' vor dem Entpacken" | $fold
  L "\
                       RESOURCE to SOURCE before extracting it.
                       ${extd}For future use.${norm}" \
    "\
                       von RESOURCE nach SOURCE herunterladen.
                       ${extd}Für zukünftige Verwendung.${norm}" | $fmt
  echo -n "  SOURCE             "
L "\`mozilla-installer' archive path. Required." \
  "Pfad für Archiv mit \`mozilla-installer'. Erforderlich." | $fold
  echo -n "                       "
L "Use \`-' for the default (Mozilla Setup Wizard" \
  "Verwenden Sie \`-' für die Standardeinstellung" | $fold
  L "\
                       directory). Use \`0' (zero) to skip the basic
                       setup. If this argument can only be resolved to
                       a directory, the newest file in this directory is
                       used (with version sort) that matches the pattern
                       \`mozilla*pc-linux*sea.t*gz'." \
    "\
                       (Verzeichnis des Mozilla-Setup-Wizards). Mit \`0'
                       (null) wird die Basis-Installation übergangen.
                       Wenn dieses Argument nur zu einem Verzeichnis
                       aufgelöst werden kann, dann wird (mit Sortierung
                       nach Versionsangabe) die neueste Datei verwendet,
                       die dem Muster \`mozilla*pc-linux*sea.t*gz'
                       entspricht." | $fmt
  echo -n "  TARGET             "
L "User-defined directory where to store the setup directory." \
  "Benutzerdefiniertes Verzeichnis, in dem das" | $fold
  L "\
                       If left out or \`-', the default (/tmp) will be
                       used. (Write permission to the specified directory
                       is required!)" \
    "\
                       Setup-Verzeichnis erstellt werden soll. Wenn dieses
                       Argument ausgelassen oder \`-' angegeben wird, so wird
                       das Standardverzeichnis (/tmp) verwendet. (Schreibrechte
                       für das angegebene Verzeichnis werden zwingend benötigt!)" | $fmt
  echo -n "
${extd}`L "PLUGIN AND ADD-ON SETUP" "INSTALLLATION VON PLUGINS UND \
ADD-ONS"`${norm}

${extd}${appname}${norm}
  [...] [( ${extd}-c${norm} | ${extd}-s${norm} | \
${extd}-l${norm} ) [SOURCE] [PLUGIN_DIR] [...] [${extd}-0o${norm}]]
  [${extd}-f${norm} [PLUGIN_DIR] [INST_PATH] [TGZ_PATH]]
  [( ${extd}-i${norm} | ${extd}-u${norm} ) [APP_NAME] [...]] \
[${extd}-d${norm} [MOZ_DIR]]

  ${extd}-c${norm}, ${extd}--copy${norm}         "
L "Copy plugin files from another installation of Mozilla or" \
  "Plugin-Dateien von einer anderen Installation von Mozilla" | $fold
L "\
                       Netscape. Mozilla will then be able to use those
                       plugins independently of the 'source' browser." \
  "\
                       oder Netscape kopieren. Mozilla kann dann diese Plugins
                       unabhängig vom 'Quell'-Browser verwenden." | $fmt
  echo -n "  ${extd}-s${norm}, ${extd}--symlink${norm}      "
L "Do not copy plugin files but create symbolic links instead." \
  "Plugin-Dateien nicht kopieren, sondern stattdessen" | $fold
L "\
                       Note that plugins are no longer available for
                       Mozilla if you eventually decide to deinstall
                       the 'source' browser." \
  "\
                       symbolische Links erzeugen. Beachten Sie, dass
                       Plugins nicht länger verfügbar sind, wenn der
                       'Quell'-Browser deinstalliert wird." | $fmt
  echo -n "  ${extd}-l${norm}, ${extd}--link${norm}         "
L "Do not copy plugin files but create hard links instead." \
  "Plugin-Dateien nicht kopieren, sondern stattdessen" | $fold
L "\
                       CAUTION! Removing one of those links will then remove
                       the plugins from two or more browsers. Restrictions to
                       hard links such as containment to one file system, will
                       also apply." \
  "\
                       (harte) Links erzeugen. VORSICHT! Das Entfernen dieser
                       Links wird dann die Plugins aus einem oder mehreren
                       Browsern entfernen. Weiterhin gelten Einschränkungen
                       für (harte) Links, wie z.B. die Beschränkung auf ein
                       Dateisystem." | $fmt
    echo -n "    SOURCE             "
L "Source plugin directory or file(s). If this is" \
  "Quelle für Plugin(s). Wenn es sich um ein Verzeichnis" | $fold
L "\
                       a directory, all files in it will be copied to
                       the specified plugin directory or (symbolic) links
                       are created there for each file. If it is a file
                       or a regular expression, only files with matching
                       names are copied/linked to. Leave this out or use
                       \`-' for the default (/usr/local/netscape/plugins),
                       which should make all Netscape plugins available
                       for this Mozilla installation." \
  "\
                       handelt, werden alle Dateien darin in das angegebene
                       Plugin-Verzeichnis kopiert bzw. dort (symbolische)
                       Links für jede Datei erzeugt. Wenn es sich um eine
                       Datei oder einen Regulären Ausdruck handelt, werden
                       nur Dateien mit passendem Namen kopiert/gelinkt.
                       Wird dieses Argument nicht oder \`-' dafür angegeben,
                       so wird der Standardwert /usr/local/netscape/plugins
                       benutzt, was alle Netscape-Plugins für diese
                       Mozilla-Installation verfügbar machen sollte."| $fmt
    echo -n "    PLUGIN_DIR         "
L "Mozilla plugin directory after installation." \
  "Mozilla-Plugin-Verzeichnis nach der Installation." | $fold
L "\
                       Leave this out or use \`-' for the default
                       (/usr/local/mozilla/plugins)." \
  "\
                       Wird dieses Argument nicht oder \`-' dafür
                       angegeben, so wird der Standardwert verwendet
                       (/usr/local/mozilla/plugins)." | $fmt
  echo -n "  ${extd}-0${norm}, ${extd}--null${norm}         "
L "Also import the libnullplugin.so file, housing" \
  "Also import the libnullplugin.so file, housing the default" | $fold
L "\
                       the default plugin that \"handles plugin data
                       for mimetypes and extensions that are not
                       specified and facilitates downloading of new
                       plugins\" (from its description).
                       CAUTION! This should only be used with newer
                       or not very older versions of Mozilla than you
                       are setting up as files of much older versions
                       and of Netscape are likely to be incompatible.
                       ${extd}For future use.${norm}" \
  "\
                       plugin that \"handles plugin data for mimetypes and
                       extensions that are not specified and facilitates
                       downloading of new plugins\" (from its description).
                       CAUTION! This should only be used with newer or not very
                       older versions of Mozilla than you are setting up as
                       files of much older versions and of Netscape are likely
                       to be incompatible. ${extd}For future use.${norm}" | $fmt
  echo -n "  ${extd}-o${norm}, ${extd}--overwrite${norm}    "
L "Overwrite existing plugins. The default is not to" | $fold
L "\
                       overwrite. ${extd}For future use.${norm}" | $fmt
  echo -n "  ${extd}-f${norm}, ${extd}--flash${norm}        "
L "Install Flash plugin using PE's Flash Plugin Installer." \
  "Install Flash plugin using PE's Flash Plugin Installer." | $fold
L "\
                       Type \`flash-linux-installer' for further information." \
  "\
                       Type \`flash-linux-installer' for further information." \
| $fmt
  echo "    PLUGIN_DIR       Mozilla plugin directory after installation. Leave this out
                       or use \`-' for the default (/usr/local/mozilla/plugins).
                       If -c, -s or -h was used before with specifying
                       PLUGIN_DIR (including \`-'), that value is used instead
                       and this option goes ignored.
    INST_PATH        PE's Flash Plugin Installer path. Leave this out or
                       use \`-' for the default (./flash-linux-installer).
    TGZ_PATH         User-defined .tar.gz file where the plugin files are
                       contained. You MUST leave the .tar.gz suffix out and the
                       respective archive MUST contain a TGZ_PATH directory to
                       contain the plugin files. Use \`-' or leave this out for
                       the default (install_flash_player_6_linux). Requires
                       Flash Plugin Installer 0.2.3b or newer to have effect.
                       ${extd}For future use.${norm}
  ${extd}-a${norm}, ${extd}--apps${norm}         Same as \`-i'.
  ${extd}-i${norm}, ${extd}--install${norm}      Install plugins and XUL \
applications from
                       cross-platform installation (XPI) files.
  ${extd}-u${norm}, ${extd}--uninstall${norm}    Uninstall XUL applications.
                       Use this with CAUTION! You may have to re-install
                       Mozilla if you uninstall a built-in application like
                       \`help' which costs you ALL plugins/apps.
                       Furthermore, some apps (e.g. \`mozgest') have their own
                       GUI-powered uninstall feature (check Edit/Preferences),
                       so you should try this first. You have been warned.
    APP_NAME           XPI file for or identifier of a XUL application. Two
                       or more (file )names are separated by spaces.
                       For both install and uninstall, all Mozilla processes
                       are terminated first. See the \`-R' option above.
                       For install, the Setup Wizard will automagically try
                       \`file.xpi' if \`file' does not exist.
                       For uninstall, a backup of chrome/installed-chrome.txt
                       will be created as chrome/installed-chrome.txt.bak file.
  ${extd}-d${norm}, ${extd}--directory${norm}    Specify user-defined Mozilla \
directory. If left out,
                       the default (/usr/local/mozilla/) will be used.
                       ${extd}For future use.${norm}
    MOZ_DIR            User-defined Mozilla directory.


${extd}EXIT CODES${norm}

  ${extd}0${norm}  Success
  ${extd}1${norm}  Required option or argument missing
  ${extd}2${norm}  \`tar' not found
  ${extd}3${norm}  \`gzip' not found
  ${extd}4${norm}  Unable to locate installer's gzip'd tarball
  ${extd}5${norm}  Unable to locate extraction target directory
  ${extd}6${norm}  General error while extracting installer tarball
  ${extd}7${norm}  Unable to locate INSTALLER executable
  ${extd}8${norm}  General error while executing INSTALLER
  "
}

function PluginImport {
  echo
  echo
  echo "${extd}Plugin import${norm}"
  local defaultImportSource="/usr/local/netscape/plugins"
  local defaultImportTarget="/usr/local/mozilla/plugins"
   
  test $verbose -eq 1 && echo "copy=$copy"
  if [ $copy -eq 1 ]; then
    echo "
Copying plugins..."
    for i in `seq 0 $copyOptLast`; do
      local importSource=""
      local importTarget=""
      test -n "${copyOpt[$i]}" && for j in ${copyOpt[$i]}; do
        if [ -z $importSource ]; then
          importSource=$j
        else
          importTarget=$j
        fi
      done
      test -z $importSource && importSource=$defaultImportSource
      test -z $importTarget && importTarget=$defaultImportTarget
      echo -n "  checking for target directory... "
      if [ -d "$importTarget" ]; then
        echo $importTarget
        echo -n "  checking for source path... "
        if [ -d "$importSource" ]; then
          echo "directory: $importSource"
          echo "  copying all plugins..."
          for j in `ls $importSource/`; do
            if [ "$j" != "libnullplugin.so" ]; then
              cp -apv $importSource/$j $importTarget
            fi
          done
          if [ $? -ne 0 ]; then
            echo "$rc_failed
            "
          else
            echo $rc_done
          fi
        elif [ -f "$importSource" ]; then
          echo "file: $importSource"
          echo "  copying $importSource..."
          cp -irpv $importSource $importTarget
          if [ $? -ne 0 ]; then
            echo "$rc_failed
            "
          else
            echo $rc_done
          fi
        else
          echo $rc_missed
        fi
      else
        echo $rc_missed
      fi
    done
  fi

  if [ $link -eq 1 ]; then
    echo "
Symlinking plugins..."
    for i in `seq 0 $linkOptLast`; do
      local importSource=""
      local importTarget=""
      test -n "${linkOpt[$i]}" && for j in ${linkOpt[$i]}; do
        if [ -z $importSource ]; then
          importSource=$j
        else
          importTarget=$j
        fi
      done
      test -z $importSource && importSource=$defaultImportSource
      test -z $importTarget && importTarget=$defaultImportTarget
      echo -n "  checking for target directory... "
      if [ -d "$importTarget" ]; then
        echo $importTarget
        echo -n "  checking for source path... "
        if [ -d "$importSource" ]; then
          echo "directory: $importSource"
          echo "  creating symbolic links for all plugins..."
          for j in `ls $importSource/`; do
            if [ "$j" != "libnullplugin.so" ]; then
              cp -asv $importSource/* $importTarget
            fi
          done
          if [ $? -ne 0 ]; then
            echo "$rc_failed
            "
          else
            echo $rc_done
          fi
        elif [ -f "$importSource" ]; then
          echo "file: $importSource"
          echo "  creating symbolic link for $importSource..."
          cp -irpsv $importSource $importTarget
          if [ $? -ne 0 ]; then
            echo "$rc_failed
            "
          else
            echo $rc_done
          fi
        else
          echo $rc_missed
        fi
      else
        echo $rc_missed
      fi
    done
  fi

  if [ $hard -eq 1 ]; then
    echo "
Hardlinking plugins..."
    for i in `seq 0 $hardOptLast`; do
      local importSource=""
      local importTarget=""
      test -n "${hardOpt[$i]}" && for j in ${hardOpt[$i]}; do
        if [ -z $importSource ]; then
          importSource=$j
        else
          importTarget=$j
        fi
      done
      test -z $importSource && importSource=$defaultImportSource
      test -z $importTarget && importTarget=$defaultImportTarget
      echo -n "  checking for target directory... "
      if [ -d "$importTarget" ]; then
        echo $importTarget
        echo -n "  checking for source path... "
        if [ -d "$importSource" ]; then
          echo "directory: $importSource"
          echo "  creating hard links for all plugins..."
          for j in `ls $importSource/`; do
            if [ "$j" != "libnullplugin.so" ]; then
              cp -lapv $importSource/* $importTarget
            fi
          done
          if [ $? -ne 0 ]; then
            echo "$rc_failed
            "
          else
            echo $rc_done
          fi
        elif [ -f "$importSource" ]; then
          echo "file: $importSource"
          echo "  creating hard link for $importSource..."
          cp -ilrpv $importSource $importTarget
          if [ $? -ne 0 ]; then
            echo "$rc_failed
            "
          else
            echo $rc_done
          fi
        else
          echo $rc_missed
        fi
      else
        echo $rc_missed
      fi
    done
  fi

  echo
}

function FlashSetup {
  echo "
${extd}Macromedia Flash plugin setup${norm}
  "
  echo -n "checking for installer path... "
  if [ -d "$flashInstPath" ]; then
    if [ -x "$flashInstPath/flash-linux-installer" ]; then
      flashInstPath="$flashInstPath/flash-linux-installer"
      echo "$flashInstPath"
    else
      flash=0
      echo $rc_missed
    fi
  elif [ -x "$flashInstPath" ]; then
    echo "$flashInstPath"
  else
    flash=0
    echo $rc_missed
  fi
  if [ $flash -ne 0 ]; then
    $flashInstPath $flashPluginDir
  else
    echo "
Could not find PointedEars' Flash Plugin Installer as
\`$flashInstPath'. Skipped.
    "
  fi

# `
}

function KillMoz {
  local result=0

  if [ -n "`ps -Af | grep mozilla-bin | grep -v grep`" ]; then
    echo -n `L "Sending all Mozilla processes the" \
               "Sende allen Mozilla-Prozessen das"`" "
    case "$1" in
      "-9") echo -n "KILL";;
         *) echo -n "TERM";;
    esac
    Lout=`L " signal" "-Signal"`
    echo -n "${Lout}... "
    killall $1 mozilla-bin 2> /dev/null
    result=$?
    if [ $result -ne 0 ]; then
      echo $rc_failed
    else
      ping=1
      mozilla -remote "ping()" 2> /dev/null
      error=$?
      test $verbose -eq 1 && echo -n $error" " >&2
      while [ $error -eq 0 ] && [ $ping -le 50 ]; do
        let ping++
        mozilla -remote "ping()" 2> /dev/null
        error=$?
        test $verbose -eq 1 && echo -n $error" " >&2
        if [ $ping -eq 25 ]; then
          echo "
          "
          L "Mozilla was pinged $ping times without response, trying
$ping more times before giving up. Press Ctrl+C to quit." \
            "Mozilla wurde $ping Mal erfolglos gepingt, es werden weitere
$ping Versuche unternommen. Drücken Sie Strg+C, um abzubrechen." | $fmt >&2
          echo -n "
... " >&2
        fi
      done
      if [ $error -ne 0 ]; then
        echo $rc_done
        test $verbose -eq 1 && \
          L "Mozilla was pinged "$ping" times until shutdown was complete." \
            "Mozilla wurde "$ping" Mal gepingt, bevor er vollständig beendet \
war." | $fmt >&2
      else
        echo $rc_failed
        test $verbose -eq 1 && \
          L "
Mozilla was pinged "$ping" times without response.
Please check your Mozilla installation." \
            "
Mozilla wurde "$ping" Mal erfolglos gepingt.
Bitte überprüfen Sie ihre Mozilla-Installation." | $fmt >&2
      fi
    fi
  fi

  return $(( $result ))
}

function RunMoz {
  # check if the current user has Mozilla already run
  # AFAIK mozilla -remote "ping()" does not pay respect to different accounts
  local chk=`ps -fu $(whoami) 2> /dev/null | grep mozilla-bin | grep -v grep`
  if [ -z "$chk" ]; then
    mozilla "$1" &
    local ping=1
    mozilla -remote "ping()" 2> /dev/null
    error=$?
    test $verbose -eq 1 && echo -n $error" " >&2
    while [ $error -ne 0 ] && [ $ping -le 50 ]; do
      let ping++
      mozilla -remote "ping()" 2> /dev/null
      local error=$?
      test $verbose -eq 1 && echo -n $error" " >&2
      if [ $ping -eq 25 ]; then
        echo "
        "
        L "Mozilla was pinged $ping times without response, trying
$ping more times before giving up. Press Ctrl+C to quit." \
            "Mozilla wurde $ping Mal erfolglos gepingt, es werden weitere
$ping Versuche unternommen. Drücken Sie Strg+C, um abzubrechen." | $fmt >&2
        echo -n "
... " >&2
      fi
    done
    if [ $error -eq 0 ]; then
      echo $rc_done
      test $verbose -eq 1 && \
        L "Mozilla was pinged "$ping" times until startup was complete." \
          "Mozilla wurde "$ping" Mal gepingt, bevor er vollständig gestartet \
war." | $fmt >&2
    else
      echo $rc_failed
      test $verbose -eq 1 && \
        L "
Mozilla was pinged "$ping" times without response.
Please check your Mozilla installation." \
          "
Mozilla wurde "$ping" Mal erfolglos gepingt.
Bitte überprüfen Sie ihre Mozilla-Installation." | $fmt >&2
    fi
  else
    mozilla -remote "openURL($1,new-tab)" &
    if [ $? -eq 0 ]; then
      echo $rc_done
    else
      echo $rc_failed
    fi
  fi
}

function XULisInstd {
  local chk="`grep chrome/$1 $mozdir/chrome/installed-chrome.txt 2> /dev/null`"
  if [ -n "$chk" ]; then
    return 0
  else
    return 1
  fi
}

function XULuninst {
  for u in $1; do if [ -n "$u" ]; then
    KillMoz
    echo -n "  $u$stat"
    if XULisInstd "$u"; then
      rm -rf $mozdir/chrome/$u* #2> /dev/null

      # Removing chrome.rdf first because overlayinfo/ is NOT automagically
      # recreated when chrome.rdf exists; otherwise an error removing
      # chrome.rdf would have "killed" $Joe_User's XUL apps without a
      # (plausible) explanation which could cause some ... trouble for this
      # $|-|3|_|_$<|21|°' |-|4><0|2.
      # See <1231960.iDbeOVK0A0@pointedears.de> pp. :->
      test $? -eq 0 && rm -f $mozdir/chrome/chrome.rdf #2> /dev/null
      test $? -eq 0 && rm -rf $mozdir/chrome/overlayinfo #2> /dev/null

      test $? -eq 0 && grep -v chrome/$u $mozdir/chrome/installed-chrome.txt \
        1> $mozdir/chrome/installed-chrome.txt.new
      # echo
      # diff -u $mozdir/chrome/installed-chrome.txt \
      #   $mozdir/chrome/installed-chrome.txt.new
      test $? -eq 0 && cp -p $mozdir/chrome/installed-chrome.txt \
        $mozdir/chrome/installed-chrome.txt.bak
      test $? -eq 0 && mv $mozdir/chrome/installed-chrome.txt.new \
        $mozdir/chrome/installed-chrome.txt
      if [ $? -eq 0 ]; then
        echo $rc_done
      else
        echo $?
        echo $rc_failed
      fi
    else
      echo "${extd}not installed${norm}"
    fi
  fi; done
}

function isMozRunning {
  # check for supported `ps' options 
  # BSD style user-oriented
  args="u "
  ps $args 1>/dev/null 2>&1
  if [ $? -eq 0 ]; then
    fallback=$args
  else
    # SysV/Unix98 (i.e. IRIX) style
    fallback="-"
    args="-f" # full output
    ps $args 1>/dev/null 2>&1
    if [ $? -eq 0 ]; then
      fallback=$args
    else
      args=$fallback
    fi
    ps $args 1>/dev/null 2>&1
    test $? -ne 0 && args=$fallback
  fi
  chk=`ps $args | grep mozilla-bin | grep -v grep`
  test -z "$chk" && return 1
  return 0
}

function XPInst {
  for i in $1; do
    # to be removed when RunMoz works instead of direct call
    # KillMoz
    local f=$i
    echo -n "  $f"
    if [ ! -f "$f" ]; then
      echo -n ".xpi$stat"
      if [ -f "$f.xpi" ]; then
        f=$f.xpi
      else
        echo "$rc_failed"
        continue
      fi
    else
      echo -n "$stat"
    fi
    if [ -f "$f" ]; then
# TO DO: Automagic uninstall requires $i = `basename $i` =~ s/-.*?\.xpi//
#       if [ `XULisInstd $(basename $i)` -eq 0 ]; then
#         echo -n "
#     $i is already installed. Performing automagic uninstall first... "
#         XULuninst "$i"
#       fi
#     if isMozRunning && mozilla -remote 'ping()' 2>/dev/null ; then
#       mozilla -remote 'openURL(file://'`pwd`'/$f)'
#     else
        mozilla "file://`pwd`/$f" # &
#     fi
      if [ $? -eq 0 ]; then
        echo "$rc_done"
      else
        echo "$rc_failed"
        return 1
      fi
    fi
  done
}

function XULsetup {
  echo "
${extd}XUL applications and cross-platform installation setup${norm}"
  
  if [ $uninst -eq 1 ]; then
    echo "
Uninstalling XUL applications (${extd}is currently tested${norm})...
    "
    XULuninst "$uninstList"
  fi
  
  if [ $inst -eq 1 ]; then
    echo "
Installing XPIs. You need to quit Mozilla after each installation.
    "
    XPInst "$instList"
  fi
}

function MozRepairFiles {
  local result=0
  for f in $1; do
    test $verbose -eq 1 && echo -n "  $f$stat"
    find $HOME/.mozilla -name "$f" -print0 2>/dev/null | xargs -0r rm -R$sVerbose
    if [ $? -eq 0 ]; then
      test $verbose -eq 1 && echo "$rc_done"
    else
      test $verbose -eq 1 && echo "$rc_failed"
      let result++;
    fi
  done
  test $verbose -eq 1 -a $result -gt 0 && \
    L "Failed to remove $result file(s)." \
      "$result Datei(en) konnte(n) nicht entfernt werden." >&2
  return $result
}

function MozRepair {
  echo "

${extd}`L "Repair of an existing installation" \
          "Reparatur einer bestehenden Installation"`${norm}
  "
  KillMoz
  test $verbose -eq 1 && sVerbose=v
  echo -n `L "Repairing" "Wird repariert"`"... "
  test $verbose -eq 1 && echo
  MozRepairFiles XUL.mfasl # chrome.rdf localstore.rdf
  sVerbose=
  if [ $verbose -eq 0 ]; then
    if [ $? -eq 0 ]; then
      echo $rc_done
    else
      echo $rc_failed
    fi
  fi
}

function UpdPerm {
  # Make XUL apps available to all users
  echo -n "`L "Updating access permissions" \
   "Zugriffsrechte werden aktualisiert"`... "
# `

  chmod -R go+r $mozdir/chrome/* 2> /dev/null
  test $? -eq 0 && chmod -R 755 $mozdir/chrome/mozgest/* 2> /dev/null
  echo $rc_done
}

# ********************************** MAIN **************************************

# Note that we use `"$@"' to let each command-line parameter expand to a
# separate word. The quotes around `$@' are essential!
# We need `tmp' as the `eval set --' would nuke the return value of getopt.

# ${extd}${appname}${norm}
#   [${extd}-?${norm}] [${extd}-v${norm}] \
# [${extd}-L${norm} LOCALE] [${extd}-I${norm} INSTALLER] [${extd}-U${norm} \
# [USER]] [${extd}-R${norm}] [${extd}-D${norm} RESOURCE]
#   [( ${extd}-c${norm} | ${extd}-s${norm} | ${extd}-h${norm} ) [SOURCE] \
# [PLUGIN_DIR] [...] [${extd}-0o${norm}]]
#   [${extd}-f${norm} [PLUGIN_DIR] [INST_PATH] [TGZ_PATH]]
#   [ ( ${extd}-i${norm} | ${extd}-u${norm} ) [APP_NAME] [...]] [${extd}-d${norm} MOZ_DIR]
#   SOURCE [TARGET]

# if `getopt -T >/dev/null 2>&1` ; [ $? = 4 ] ; then
#   echo "Enhanced getopt(1)"
#   tmp=`getopt -o hvL:I:U::RD:c:s:l:0of::a::i::u::d: \
#               --long help,verbose,locale,installer,user,repair,download,copy,\
# symlink,link,null,overwrite,flash,apps,install,uninstall,directory \
#               -n "$appname" -s bash \
#               -- "$@"`
#   echo "$tmp"
#   exit 0
# else
#   echo "Old getopt(1)"
#   tmp=`getopt hvL:I:U:RD:c:s:l:0iof:a:i:u:d: "$@"`
# fi
#
# getopt_exit_code=$?
# if [ $getopt_exit_code -eq 0 ]; then
##     getopt  returns  error  code 0 for successful parsing, 1 if
##     getopt(3) returns errors, 2 if it does not understand  its
##     own parameters, 3 if an internal error occurs like out-of-
##     memory, and 4 if it is called with -T.
#
# Note the quotes around `$tmp': they are essential!
#   echo $tmp
  # remove "--"
#   for i in $tmp; do if [ "$i" != "--" ]; then tmp2="${tmp2} $i"; fi; done
#   eval set -- "$tmp2"
#   echo $*
  #exit 0
# else
#   echo "getopt exited: $getopt_exit_code
#   " >&2
#   exit $getopt_exit_code
# fi

# L10n
lg=""
if [ -n "$LANG" ]; then lg=`echo $LANG | sed 's/_.*[.].*//' 2> /dev/null`; fi
if [ -z "$lg" ]; then lg=`echo $LC_CTYPE | sed 's/_.*//' 2> /dev/null`; fi

# from /etc/rc.status

if test -z "$LINES" -o -z "$COLUMNS" ; then
    eval `stty size 2>/dev/null | (read L C; \
	  echo LINES=${L:-24} COLUMNS=${C:-80})`
fi
test $LINES   -eq 0 && LINES=24
test $COLUMNS -eq 0 && COLUMNS=80

if test "$TERM" != "raw" && stty size >/dev/null 2>&1 ; then
  esc=`echo -en "\033"`
  extd="${esc}[1m"
  warn="${esc}[1;31m"
  done="${esc}[1m"
  attn="${esc}[1m"
  norm=`echo -en "${esc}[m\017"`
  stat=`echo -en "\015${esc}[${COLUMNS}C${esc}[14D "`
else
  esc=""
  extd=""
  warn=""
  done=""
  attn=""
  norm=""
  stat="... "
fi

# check for fold
  fold="fold -sw $COLUMNS"
  chk=`which fold 2> /dev/null`
  test $? -ne 0 && fold="cat"
  chk=`echo x | $fold 1> /dev/null`
  test -n "$chk" && fold="cat"

# check for fmt
  fmt=cat
  if [ $COLUMNS -ne 80 ]; then # output is preformatted for 80 cols
    chk=`which fmt 2> /dev/null`
    if [ $? -ne 0 ]; then
      fmt=$fold
    else
      # check for columns
      fmt="fmt -$COLUMNS"
      chk=`echo x | $fmt 2> /dev/null`
      test -z "$chk" && fmt="fmt"
      # check for -c|--crown-margin
      chk=`echo x | $fmt -c 2> /dev/null`
      if [ -n "$chk" ]; then
        fmt=$fmt" -c"
      else
        chk=`echo x | $fmt --crown-margin 2> /dev/null`
        test -n "$chk" && fmt=$fmt" --crown-margin"
      fi
    fi
  fi

echo "
${extd}Mozilla Setup Wizard for GNU/Linux $ver${norm}
Copyright (C) $copy  Thomas Lahn <$mail>
Distributed under the terms of the GNU General Public License (GPL),
see COPYING file or http://www.fsf.org/copyleft/gpl.html for details."

help=0
test -z "$1" && help=1

# Flags and setup data
verbose=0
repair=0
single=0
src=""
target=""
installer="mozilla-installer"
import=0
importNull=0
copy=0
copyOpt[0]=""
copyOptLast=-1
link=0
linkOpt[0]=""
linkOptLast=-1
hard=0
hardOpt[0]=""
hardOptLast=-1
overwrite=0
flash=0
flashOpt=""
inst=0
instList=""
uninst=0
uninstList=""
last=""

while [ -n "$1" ]; do
  case "$1" in
    "-?" | --help)        help=1;;
    -v   | --verbose)
      last=""
      verbose=1
      echo
      echo "${extd}Working in verbose mode.${norm}
\$* = \"$*\"
      ";;
           -L | --locale)      last="L";;
           -R | --repair)      last=""; repair=1;;
           -I | --installer)   last="I";;
           -U | --single-user) last=""; single=1;;
    -0        | --null)        last=""; importNull=1;;
    -O   | -o | --overwrite)   last=""; overwrite=1;;
    -C   | -c | --copy)        last="c"; import=1; copy=1; let copyOptLast+=1;;
    -S   | -s | --symlinks)    last="s"; import=1; link=1; let linkOptLast+=1;;
    -H   | -h | --hardlinks)   last="h"; import=1; hard=1; let hardOptLast+=1;;
    -F   | -f | --flash)       last="f"; flash=1; flashPluginDir=""
                                 flashInstPath="";;
    -A   | -a | --apps | -i | --install)
                               last="i"; inst=1;;
           -u | --uninstall)   last="u"; uninst=1;;
    *)
      if [ -n "$last" ]; then
        case $last in
          L)
            lg=$1
            last="";;
          I)
            installer=$1
            last="";;
          c)
            if [ -z "${copyOpt[$copyOptLast]}" ]; then
              copyOpt[$copyOptLast]=$1
            else
              copyOpt[$copyOptLast]="${copyOpt[$copyOptLast]} $1"
              last=""
            fi;;
          s)
            if [ -z "${linkOpt[$linkOptLast]}" ]; then
              linkOpt[$linkOptLast]=$1
            else
              linkOpt[$linkOptLast]="${linkOpt[$linkOptLast]} $1"
              last=""
            fi;;
          h)
            if [ -z "${hardOpt[$hardOptLast]}" ]; then
              hardOpt[$hardOptLast]=$1
            else
              hardOpt[$hardOptLast]="${hardOpt[$hardOptLast]} $1"
              last=""
            fi;;
          f)
            if [ -z "$flashPluginDir" ]; then
              flashPluginDir=$1
            else
              test -z "$flashInstPath" && flashInstPath=$1
              last=""
            fi;;
          i)
            test -n "$instList" && instList="$instList "
            instList="$instList$1";;
          u)
            test -n "$uninstList" && uninstList="$uninstList "
            uninstList="$uninstList$1";;
        esac
      else
        if [ -z "$src" ]; then
          src="$1"
        else
          test -z "$target" && target="$1"
        fi
      fi
      ;;
  esac
  shift
done

     rc_done="${done}done${norm}"
  rc_running="${stat}${done}`L 'running         ' 'läuft         '`${norm}"
   rc_failed="${warn}`L 'failed        ' 'versagt       '`${norm}"
   rc_missed="${warn}`L 'not found     ' 'nicht gefunden'`${norm}"
  rc_skipped="${attn}`L 'skipped       ' 'übergangen    '`${norm}"
  rc_done_up="${esc}[1A${rc_done}"
rc_failed_up="${esc}[1A${rc_failed}"

test -z "$src" && src="-"
test -z "$target" && target="-"
if [ $verbose -eq 1 ]; then
  echo "src=\"$src\"
target=\"$target\"
installer=\"$installer\""
fi

test -z "$flashPluginDir" -o "$flashPluginDir" = "-" &&
flashPluginDir="/usr/local/mozilla/plugins"
test -z "$flashInstPath" -o "$flashInstPath" = "-" &&
flashInstPath="./flash-linux-installer"
if [ $verbose -eq 1 ]; then
  echo -n "import=$import
copy=$copy
copyOpt="
  test -n "$copyOpt" && for i in `seq 0 $copyOptLast`; do echo -n
"[\"${copyOpt[$i]}\"] "; done
  echo -n "
copyOptLast=$copyOptLast
link=$link
linkOpt="
  test -n "$linkOpt" && for i in `seq 0 $linkOptLast`; do echo -n
"[\"${linkOpt[$i]}\"] "; done
  echo -n "
linkOptLast=$linkOptLast
hard=$hard
hardOpt="
  test -n "$hardOpt" && for i in `seq 0 $hardOptLast`; do echo -n
"[\"${hardOpt[$i]}\"] "; done
  echo "
hardOptLast=$hardOptLast
overwrite=$overwrite
flash=$flash
flashPluginDir=\"$flashPluginDir\"
flashInstPath=\"$flashInstPath\"
inst=$inst
instList=\"$instList\"
uninst=$uninst
uninstList=\"$uninstList\"
  "
fi

# check for required arguments
if [ $inst -eq 1 ] && [ -z "$instList" ]; then
  echo "${appname}: Required argument missing for -A|--apps|-i|--install" >&2
  echo
  help=1
fi

if [ $uninst -eq 1 ] && [ -z "$uninstList" ]; then
  echo "${appname}: Required argument missing for -u|--uninstall" >&2
  echo
  help=1
fi

test $help -eq 1 && help
echo "Send suggestions and bug reports to <$mail_feedback>
"
test $help -eq 1 && exit 1

echo "
${extd}`L "Basic Setup" "Basis-Installation"`${norm}"
echo

if [ "$src" = "0" ]; then
  echo `L "Skipped" "Übergangen"`.
else
  echo -n "`L 'checking for tar...               ' 'überprüfe auf tar...              '`"
  chk=`which tar 2> /dev/null`
  if [ $? -eq 0 ]; then
    echo "`tar --version | head -n 1 -` ($chk)"
  else
    echo "$rc_missed
    "
    echo "${appname}: Could not find \`tar' which is required to extract \
the archive." >&2
    exit 2
  fi

  echo -n "`L 'checking for gzip...              ' 'überprüfe auf gzip...             '`"
  chk=`which gzip 2> /dev/null`
  if [ $? -eq 0 ]; then
    echo "`gzip --version | head -n 1 -` ($chk)"
  else
    echo "$rc_missed
    "
    echo "${appname}: Could not find \`gzip' which is required to extract \
the archive." >&2
    exit 3
  fi

  echo -n "`L 'checking for source path...       ' 'überprüfe Quellpfad...            '`"
  if [ "$src" = "-" ]; then
    src=`dirname $0`
  fi
  if [ -d "$src" ]; then
    echo "`L directory Verzeichnis`: $src" | fold -s
    echo -n "`L 'checking for archive...           ' 'überprüfe Archiv...               '`"
    srcf=`(ls -1vr $src/mozilla*pc-linux*sea.t*gz 2> /dev/null) | head -n 1 -`
    if [ -n "$srcf" ]; then
      echo "$srcf"
      src=$srcf
    else
      echo "$rc_missed
      "
      exit 4
    fi
  else
    echo "file: $src"
    echo -n "`L 'checking for archive...           ' 'überprüfe Archiv...               '`"
    if [ -f "$src" ]; then
      echo $rc_done
    else
      echo "$rc_missed
      "
      exit 4
    fi
  fi

  echo -n "checking for target directory...  "
  if [ "$target" = "-" ]; then
    target="/tmp"
  fi

  if [ -d "$target" ]; then
    echo $target
    if [ $verbose -eq 1 ]; then
      echo "extracting files..."
      tar xvzf $src -C $target
    else
      echo -n "extracting files...               "
      tar_out=`tar xvzf $src -C $target 2>&1`
    fi
    if [ $? -ne 0 ]; then
      echo "$rc_failed
      "
      if [ $verbose -eq 0 ]; then echo "$tar_out"; fi
      echo
      exit 6
    else
      echo $rc_done
    fi
    echo -n "checking for $installer... "
    if [ -f "$target/$installer/$installer" ] \
      && [ -x "$target/$installer/$installer" ]; then
      echo $rc_done
      KillMoz
      echo -n "
Installing `grep mozilla/ $target/$installer/config.ini | uniq | \
sed 's%.*mozilla/\(.*\)/linux-xpi/%\1%'`.
Waiting for \`$installer' to finish
(close all Mozilla windows to continue!)... "
# `

      # save current working directory before changing it (fixes XPI setup bug)
      cwd=`pwd 2> /dev/null`

      cd $target/$installer/
      out="`./$installer 2>&1`"
      if [ $? -eq 0 ]; then
        echo $rc_done; echo
        test -n "$out" && echo "
$out
        "
        # check if `df' is supported
        chk="`df "$target" 2>/dev/null`"
        if [ $? -eq 0 ]; then
          # check if -h option is supported
          chk2="`df -h "$target" 2>/dev/null`"
          if [ $? -eq 0 ]; then
            chk="$chk2"
          else
            # check if --human-readable option is supported
            chk2="`df --human-readable "$target" 2>/dev/null`"
            test $? -eq 0 && chk="$chk2"
          fi
          test -n "$chk" && echo "$chk
          "
        fi
        answer="0"
        while [ "$answer" != "y" ] && [ "$answer" != "n" ]; do
          read -p "Clean up NOW ([y]es | [n]o | [i]nfo)? " -n 1 answer
          echo
          case "$answer" in
            y)
              echo
              echo -n "cleaning up... "

              # up one directory before removal (secure method)
              cd ..

              out="`rm -r $target/$installer 2>&1`"
              if [ $? -eq 0 ]; then
                echo $rc_done
              else
                echo $rc_failed
                test -n "$out" && echo "
$out
                "
              fi
              break;;
            n)
              echo "
--------------------------------------------------------------------
OK. If not needed anymore, you should

  rm -r $target/$installer

to free disk space.
--------------------------------------------------------------------"
              break;;
            i)
              echo "
--------------------------------------------------------------------
\"Yes\" means that the setup directory extracted from the archive will
be removed to free disk space.

\"No\" keeps the setup files and allows you to reinstall Mozilla with

  $target/$installer/$installer

if something goes wrong.
--------------------------------------------------------------------
              " | $fmt
              ;;
          esac
        done

        # back to previous directory
        test -n "$cwd" && cd "$cwd"
      else
        echo $rc_failed
        test -n "$out" && echo "
$out
        "
        exit 8
      fi
    else
      echo "${warn}not found or executable bit not set${norm}
      "
      exit 7
    fi
  else
    echo "$rc_missed

${appname}: ${target}: Unable to find target directory.
    "
    exit 5
  fi
fi

test $import -eq 1 && PluginImport
test $flash -eq 1 && FlashSetup

# for 0.3.5: customizable by `-d' option
mozdir=/usr/local/mozilla

test $uninst -eq 1 -o $inst -eq 1 && XULsetup
test $repair -eq 1 && MozRepair

echo "

${extd}`L "Finalizing setup" "Installation wird abgeschlossen"`${norm}
"
UpdPerm

echo "

${extd}`L "Setup finished" "Installation beendet"`.${norm}
"
