#! /bin/bash

# ViaVoice environment installation script
VERSION=1.9
# Copyright 2003, Carlo Wood <carlo@alinoe.com>

# You can edit this section.

# The directory where we can read the ViaVoice RPMs from.
VIAVOICERPMDIR=`pwd`/redhat
# A mirror of the blackdown JDK-1.2.2 RC4 directory.
JDKMIRROR="ftp://ftp.skynet.be/pub/ftp.blackdown.org/JDK-1.2.2/i386/rc4"
# A RedHat mirror.
REDHATMIRROR="ftp://ftp.nluug.nl/site/ftp.redhat.com/pub/redhat/linux"
# Installation prefix.
INSTALLDIR="/usr/local/viavoice/redhat-6.2"

#------------------------------------------------------------------------------
# Nothing below this line should need editting.

# This script installs the ViaVoice rpms, as released originally by IBM,
#
# ViaVoice_runtime-3.0-1.2.i386.rpm		The runtime package.
# ViaVoice_TTS_rtk-5.1-1.2.i386.rpm		The Text To Speech runtime kit.
# ViaVoice_Dictation-1.0-1.0.i386.rpm		The dictation application.
# dict.lic.ila.txt				The overall license file.
#
# ViaVoice is no longer maintained by IBM.  It seems that you even cannot buy
# it anymore!  The older rpms listed above are based on, developed on and
# tested on redhat 6.2 using the blackdown jdk-1.2.2-RC4 java version.
# On more modern systems, like systems that are based on glibc-2.3 (ie RH9)
# these rpms will not work at all anymore.  It is needed to link them with
# an older glibc.
#
# This script installs the ViaVoice rpms as normal, but installs the original
# RedHat 6.2 files and the blackdown java in a special directory (INSTALLDIR).
# The ViaVoice start-scripts are then patched to use this environment.  The
# RedHat 6.2 rpms that are installed are not installed as rpms (you won't see
# them back with rpm -qa) and can be easily gotten rid of by just removing
# the whole directory (INSTALLDIR).
# The files in INSTALLDIR are also patched, most notably because they
# contain two hardcoded paths to files: the dynamic linker and the
# Bourne shell (/bin/sh).  Because we have to change the binaries, there
# is no space to make these paths longer than they already are.  Therefore
# they are changed into '/tmp/ld-vvlnx.so.2' and '/tmp/vv' respectively,
# having the same original length.  Those two are then set to be symbolic
# links to the real dynamic linker and shell to be used.
# Note that ALSA (Advanced Linux Sound Architecture), the sound drivers that
# replace the older OSS as of kernel 2.5, also introduce a problem for some
# soundcards: unlike the OSS drivers, the ALSA drivers limit the recording
# buffer to the hardware limit of your sound card.  For example, the SB Live!
# only has two 'period' buffers (called fragments before), and although
# viavoice requests an 'arbitrary number of periods, size 1024 bytes', it
# only gets two periods of 1024 bytes: 2048 bytes in total!  The ViaVoice
# engine however doesn't even process sound until it sees at least 6102 bytes.
# The 'solution' for this is to increase the buffer size (from 1024 to say
# 8192), this script also takes care of that.  Unfortunately, also that is
# possibly not enough: the sound is read from the hardware in chunks of
# 'period size' and having only two buffers this is often causing an underrun.
# When ALSA sees an underrun... it stops the sound stream.
# While this script works for me - you might still run into this problem.
# The problem can easily be detected by attaching the ViaVoice 'engine'
# with 'strace' once it runs and see if it reads the dsp device or not,
# or that all it does is calling ioctl without ever trying to read(2)
# something.  I reported this difference between OSS and ALSA's OSS emulation
# to the ALSA developers and they 'fixed' it in the current CVS of ALSA
# (should be fixed in 0.9.6).  But... you guess it, it still doesn't work.
# At the moment I am working on a real solution for ALSA which will be used
# by 'vvinstall2'; this script will be for the newer ViaVoice rpms that came
# with the 'mandrake 8.0 power edition' however.
#

# This script needs the following rpms to be installed:

# Using RedHat 9:
#
# rpm-4.2-1.i386.rpm
# bash-2.05b-20.i386.rpm
# grep-2.5.1-7.i386.rpm
# which-2.14-5.i386.rpm
# sed-4.0.5-1.i386.rpm
# tar-1.13.25-11.i386.rpm
# sudo-1.6.6-3.i386.rpm
# ncftp-3.1.5-4.i386.rpm
# cpio-2.5-3.i386.rpm
# vim-common-6.1-29.i386.rpm
# coreutils-4.5.3-19.i386.rpm (for mv, rm, cp, chmod, cat, id, ln,
#                                  pwd, md5sum, wc, tee and install).

# Using RedHat 8.0:
#
# Same rpms, different versions; except
# that instead of coreutils- you will have
#
# fileutils-4.1.9-11.i386.rpm (for mv, rm, cp, chmod, ln and install).
# textutils-2.0.21-5.i386.rpm (for cat, md5sum and wc).
# sh-utils-2.0.12-3.i386.rpm (for id, pwd and tee).

# Mandrake and other versions of RedHat:
#
# Actually, the versions of these rpms are not important.
# Just run the script and it will tell you if anything is
# missing.

# The shell commands used in this script.
COMMANDS="bash sh ln rpm mv rm cp chmod cat grep egrep which sed"
COMMANDS="$COMMANDS id pwd sudo md5sum wc tee tar ncftpget cpio xxd"

# Rpms needed by this script.
RPMS="rpm bash grep which sed tar sudo ncftp cpio vim-common"

# Location of a temporary file.
TMPOUT=/tmp/vvinstall.out

# If '/etc/sudoers' doesn't contain "NOPASSWD:" then
# sudo will ask for a password using this prompt:
SUDO_PROMPT="The password for sudo has timed out."
SUDO_PROMPT="$SUDO_PROMPT  Please reentered the password for %u: "
export SUDO_PROMPT

# These are the rpms that need to be installed in the INSTALLDIR directory.
VVRPMS="glibc-2.1.3-15.i386.rpm"
VVRPMS="$VVRPMS libtermcap-2.0.8-20.i386.rpm"
VVRPMS="$VVRPMS XFree86-libs-3.3.6-20.i386.rpm"
VVRPMS="$VVRPMS libstdc++-2.9.0-30.i386.rpm"
VVRPMS="$VVRPMS sh-utils-2.0-5.i386.rpm"
VVRPMS="$VVRPMS bash-1.14.7-22.i386.rpm"
VVRPMS="$VVRPMS fileutils-4.0-21.i386.rpm"
NUMRPMS=7
if test -n "$VVINSTALLMAINTAINER"; then
VVRPMS="$VVRPMS glibc-devel-2.1.3-15.i386.rpm"
VVRPMS="$VVRPMS strace-4.2-1.i386.rpm"
NUMRPMS=9
COMMANDS="$COMMANDS find"
RPMS="$RPMS findutils"
fi

# Get rid of any aliases and functions.
unalias -a
COMMANDSRE=`echo $COMMANDS | sed -e 's/ /|/g'`
unset `declare -fF | egrep ' ('$COMMANDSRE'|cd|echo|test)$' | sed -e 's/.* //'`

function failure() {
  echo "FAILURE";
  if test "x$1" != "x"; then
    echo "$1";
  fi
  echo "$2  Aborting.";
  rm -f $TMPOUT 2>/dev/null
  exit 1;
}

#------------------------------------------------------------------------------
# Test if the commands that are used in this script are available.

echo -n "Checking if the rpms needed by this script are installed... "

# Check if 'rpm' is available.
(rpm --version | grep 'RPM version') >/dev/null 2>/dev/null ||
  failure "" "This script only works on a machine with 'rpm' installed."

# Check if each needed rpm is installed.
(echo -n > $TMPOUT) 2>/dev/null || failure "" "First remove $TMPOUT, it is in the way."
for cmd in $RPMS; do
  rpm -q $cmd >> $TMPOUT || failure \
    "`rpm -q $cmd`" "Please install the '"$cmd"' rpm before continuing."
done
echo "OK"
# At the end, print the installed versions.
cat $TMPOUT | sed -e 's/^/    /'

echo -n "Checking if the commands needed by this script are in your PATH... "
(which --version | grep GNU) >/dev/null 2>/dev/null ||
  failure "" "The 'which' command doesn't work!"
which $COMMANDS >/dev/null 2>/dev/null || failure \
  "`which $COMMANDS 2>&1 >/dev/null`" \
  "$? commands are not in your PATH!"

echo -ne "OK\nChecking if the commands needed by this script execute... "
for cmd in $COMMANDS; do
  if test "$cmd" = "ncftpget"; then
    (ncftpget --version | grep NcFTPGet) >/dev/null 2>/dev/null ||
      failure "" "Command 'ncftpget' failed to execute!"
  else
    (if test "$cmd" = "sudo"; then
       $cmd -V
     elif test "$cmd" = "pwd"; then
       pwd
     else
       $cmd --version
     fi) > $TMPOUT 2>&1 ||
       failure "`cat $TMPOUT`" "Command '$cmd' failed to execute!"
  fi
done

#------------------------------------------------------------------------------
# Sanity checks.

echo -ne "OK\nDoing some sanity checks... "
test `id -u` = 0 && failure "" "Don't run this script as root!"
(cd ~ && test `pwd` = $HOME) 2>/dev/null ||
  failure "" "Problem determining HOME directory!"
rm -f $TMPOUT; test -e $TMPOUT &&
  failure "" "Temporary file '$TMPOUT' exists and cannot be removed!"
(echo "Jesus loves you" > $TMPOUT &&
    test "`cat $TMPOUT`" = "Jesus loves you") ||
  failure "" "Temporary file '$TMPOUT' cannot be created!"
rm -f troep 2>/dev/null ||
  failure "" "File 'troep' exists and cannot be removed!"
(echo "Hugs and kisses" > troep &&
    test "`cat troep`" = "Hugs and kisses") 2>/dev/null ||
  failure "" "Current directory is not writable!"
rm troep
test -z "$INSTALLDIR" && failure "INSTALLDIR is not set?!"
SPACE=`echo "$INSTALLDIR" | grep '[[:space:]]' 2>/dev/null`
test -z "$SPACE" || failure "" "INSTALLDIR may not contain spaces!"
INSTALLDIRMD5=`echo $INSTALLDIR | md5sum`
if test -e $INSTALLDIR; then
  if test ! -e .installdir || test -z "$INSTALLDIRMD5" ||
    test "$INSTALLDIRMD5" != "`cat .installdir`"; then
      ERRMSG="Directory $INSTALLDIR already exists!  "
      ERRMSG="$ERRMSG Cowardly refusing to remove it.  Please remove it first."
      failure "" "$ERRMSG"
  fi
else
  echo "$INSTALLDIRMD5" > .installdir
fi

#------------------------------------------------------------------------------
# Check if we have all ViaVoice rpms.

echo -ne "OK\nChecking contents of VIAVOICERPMDIR ($VIAVOICERPMDIR)... "
# This script uninstalls the ViaVoice rpms, make sure we (still) have
# these rpms so they can be reinstalled.
for f in dict.lic.ila.txt \
         ViaVoice_runtime-3.0-1.2.i386.rpm \
         ViaVoice_TTS_rtk-5.1-1.2.i386.rpm \
	 ViaVoice_Dictation-1.0-1.0.i386.rpm; do
  test -f $VIAVOICERPMDIR/$f ||
    failure "" "Expected file \"$VIAVOICERPMDIR/$f\" not found!"
done
(cd $VIAVOICERPMDIR; echo -e "\
440ef558e698c9a15cdbb785c0f551f7  dict.lic.ila.txt\n\
ae6e5b39d826e5c7dc08bbd52fe250b2  ViaVoice_runtime-3.0-1.2.i386.rpm\n\
5063bbdb272669a0a048b02f16536d53  ViaVoice_TTS_rtk-5.1-1.2.i386.rpm\n\
65a9f3161c69e7178f48e6343c9ff253  ViaVoice_Dictation-1.0-1.0.i386.rpm" |
  md5sum -c 2>/dev/null | sed -e 's/^/    /' |
  tee $TMPOUT | grep 'OK$' | wc --lines | grep '4$' >/dev/null) ||
  failure "`grep FAILED $TMPOUT`" "Checksum of files in $VIAVOICERPMDIR failed!"

#------------------------------------------------------------------------------
# Remove previous installation.

echo -ne "OK\nChecking usability of sudo... "
ERRMSG="There is a problem with the configuration of sudo: read 'man sudo' "
ERRMSG="$ERRMSG and give yourself full permissions."
(sudo -p 'Give password of %u: ' -l |grep '[^A-Z]ALL[^A-Z]') >/dev/null 2>&1 ||
  failure "" "$ERRMSG"
(sudo id -u > sudo.test && test `cat sudo.test` = "0") ||
  failure "" "Failed to execute sudo!"
sudo rm sudo.test
sudo -v

# We can't be too cautious here.
# Note that normally this is impossible anyway: we only get here when
# INSTALLDIR is equal to a previously non-existing directory (see test
# with INSTALLDIRMD5 above).
if test "$INSTALLDIR" = "/" -o "$INSTALLDIR" = "/usr" \
    -o "$INSTALLDIR" = "/usr/local"; then
  echo -e "ARGH!"
  echo -n "Helllo??? Are you crazy to set INSTALLDIR to \"$INSTALLDIR\"?  "
  echo "We will REMOVE that directory!"
  exit 1
fi
if test -e $INSTALLDIR; then
  echo -ne "OK\nDeleting installation directory ($INSTALLDIR)... "
  sudo rm -rf "$INSTALLDIR" ||
    failure "" "Failed to remove old installation directory ($INSTALLDIR)."
fi

# Remove the ViaVoice rpms if they are installed.
echo -ne "OK\nRemoving old ViaVoice rpms... "
OLDRPMS=`rpm -q viavoicemenu_us ViaVoice_Dictation ViaVoice_TTS_rtk \
ViaVoice_runtime_US_LangPack ViaVoice_runtime |
  grep -v 'not installed'`
if test -z "$OLDRPMS"; then
  echo "None installed"
else
  for i in $OLDRPMS; do
    echo -n $i" ";
    sudo rpm -e --nodeps --noscripts $i ||
      failure "" "Failed to erase old installation."
    echo -n "OK, "
  done
  echo "done."
fi

#------------------------------------------------------------------------------
# Do we have ALSA?

sudo modprobe snd >/dev/null 2>/dev/null
if test -e /proc/asound; then
  echo "You are using the ALSA drivers."
sudo rm -f alsatest.$$.c alsatest.$$
cat > alsatest.$$.c << EOF
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include <sys/soundcard.h>
#include <time.h>

int main(void)
{
  int fd;
  int res = 0x7fff0009;
  audio_buf_info info;
  int prev_size = 0;
  do
  {
    ++res;
    close(fd);
    fd = open("/dev/dsp", O_RDONLY);
    if (fd == -1) { perror("open"); exit(127); }
    if (ioctl(fd, SNDCTL_DSP_SETFRAGMENT, &res) == -1) {
      perror("ioctl"); exit(127); }
    if (ioctl(fd, SNDCTL_DSP_GETISPACE, &info) == -1) {
      perror("read"); exit(127); }
    printf("    Allocated %d buffers of %d bytes.\n", info.fragstotal, info.fragsize);
    if (prev_size == info.fragsize * info.fragstotal)
    {
      if (info.fragsize * info.fragstotal < 8192)
      printf("    It seems impossible to set a recording buffer with a\n"
             "    total size of at least 8192 bytes.  This is not going\n"
             "    to work with ViaVoice.  Sorry.\n");
      else
      {
        printf("    It seems impossible to set a recording buffer with a\n"
             "    that is sufficiently large.  It is very likely that you\n"
             "    will run into problems with viavoice (buffer overruns)\n");
        exit(0);
      }
      exit(126);
    }
    prev_size = info.fragsize * info.fragstotal;
  }
  while (info.fragsize * (info.fragstotal - 1) < 8192);
  printf("    Successfully allocated a buffer that is large enough.\n");
  fprintf(stderr, "%02x\n", res & 0xff);
  res = AFMT_S16_LE;
  if (ioctl(fd, SNDCTL_DSP_SETFMT, &res) == -1) {
    perror("ioctl"); exit(127); }
  res = 0;
  if (ioctl(fd, SNDCTL_DSP_STEREO, &res) == -1) {
    perror("ioctl"); exit(127); }
  res = 22050;
  if (ioctl(fd, SOUND_PCM_READ_RATE, 0xbfffdcfc) == -1) {
    perror("ioctl"); exit(127); }
  char buf[1024];
  if (read(fd, buf, sizeof(buf)) < 0) { perror("read"); exit(0); }
  static struct timespec naptime = { 0, 100000000 };
  int count = 0;
  do {
    if (ioctl(fd, SNDCTL_DSP_GETISPACE, &info) == -1) {
      perror("read"); exit(127); }
    nanosleep(&naptime, 0);
    if (++count == 20) { printf("Failed to cause an xrun.\n"); exit(0); }
  } while(info.bytes < info.fragsize * info.fragstotal);
  printf("    Successfully caused an xrun.\n");
  printf("    non-blocking fragments: %d\n", info.fragments);
  printf("    non-blocking bytes: %d\n", info.bytes);
  ssize_t bufsize = info.bytes;
  ssize_t trlen = 0;
  int nf = 0;
  for (;;)
  {
    if (info.fragments > 0) {
      ssize_t rlen;
      if ((rlen = read(fd, buf, sizeof(buf))) < 0)
      { perror("read"); exit(127); }
      trlen += rlen;
      if (trlen > bufsize) {
        printf("    Read %d bytes: stream successfully restarted.\n", trlen);
	break;
      }
      nf = 0;
    }
    else if (++nf > 10) {
      printf("    Stream is not restarted after xrun.\n");
      exit(1);
    }
    if (ioctl(fd, SNDCTL_DSP_GETISPACE, &info) == -1) {
      perror("read"); exit(127); }
  }
  close(fd);
  return 0;
}
EOF
gcc alsatest.$$.c -o alsatest.$$ ||
  failure "" "Failed to compile ALSA test program."
alsatest.$$ 2> $TMPOUT; RESULT="$?"
ALSASIZECODE=`cat $TMPOUT`
rm alsatest.$$ alsatest.$$.c
test $RESULT -eq 126 && failure "" "Incompatible hardware, use OSS instead of ALSA."
test $RESULT -eq 127 && failure "" "Failed to run ALSA test program."
if test $RESULT -eq 1; then
  echo "Your ALSA kernel modules are buggy."
#  echo -n "You need to apply the patch from "
#  echo "http://www.xs4all.nl/~carlo17/alsa/ossfix.diff "
#  echo "to your kernel and recompile/install/reload the kernel modules."
fi
fi

#------------------------------------------------------------------------------
# Download missing files.

echo "Downloading files that need to be installed..."
for url in \
$JDKMIRROR/jdk-1.2.2-RC4-glibc-2.1.2.md5 \
$JDKMIRROR/jdk-1.2.2-RC4-linux-i386-glibc-2.1.2.tar.bz2 \
; do
  FILE=`echo $url | sed -e 's%.*/%%'`
  if ! test -f $FILE; then
    ncftpget $url || failure "Failure to download $FILE."
  else
    echo "    Already have $FILE"
  fi
done
for f in $VVRPMS; do
  if ! test -f $f; then
    ncftpget $REDHATMIRROR/6.2/en/os/i386/RedHat/RPMS/$f ||
      failure "" "Failure to download $f."
  else
    echo "    Already have $f"
  fi
done
echo -n "Checking integrity of these files... "
(grep 'jdk-1.*bz2' jdk-1.2.2-RC4-glibc-2.1.2.md5 | md5sum -c 2>/dev/null |
    sed -e 's/^/    /' | tee $TMPOUT | grep 'OK$') >/dev/null ||
  failure "`grep FAILED $TMPOUT`" "Checksum failed!"
(rpm --checksig $VVRPMS | sed -e 's/^/    /' | tee $TMPOUT | grep 'md5' |
    wc --lines | grep "$NUMRPMS"'$' >/dev/null) ||
  failure "`grep 'NOT OK' $TMPOUT`" "Checksum of RedHat 6.2 rpms in failed!"
echo OK

#------------------------------------------------------------------------------
# (Re)install everything.

echo -n "Installing java components, please wait... "
sudo mkdir -p $INSTALLDIR
sudo tar -C $INSTALLDIR -xjf jdk-1.2.2-RC4-linux-i386-glibc-2.1.2.tar.bz2 ||
  failure "" "Installation of jdk failed."
echo -ne "OK\nInstalling glibc-2.1.3 lib/* libraries... "
rpm2cpio glibc-2.1.3-15.i386.rpm |
    (cd $INSTALLDIR && sudo cpio -id 'lib/*') >/dev/null 2>/dev/null ||
  failure "" "Installation of glibc failed."
if test -n "$VVINSTALLMAINTAINER"; then
echo -ne "OK\nInstalling glibc-devel-2.1.3... "
rpm2cpio glibc-devel-2.1.3-15.i386.rpm |
    (cd $INSTALLDIR && sudo cpio -id 'usr/lib/*' 'usr/include/*') >/dev/null 2>/dev/null ||
  failure "" "Installation of glibc-devel failed."
fi
echo -ne "OK\nInstalling XFree86 libraries... "
rpm2cpio XFree86-libs-3.3.6-20.i386.rpm |
    (cd $INSTALLDIR && sudo cpio -id) >/dev/null 2>/dev/null ||
  failure "" "Installation of XFree86-libs failed."
echo -ne "OK\nInstalling libstdc++... "
rpm2cpio libstdc++-2.9.0-30.i386.rpm |
    (cd $INSTALLDIR && sudo cpio -id) >/dev/null 2>/dev/null ||
  failure "" "Installation of libstdc++ failed."
echo -ne "OK\nInstalling bash, sleep and cp... "
rpm2cpio bash-1.14.7-22.i386.rpm |
    (cd $INSTALLDIR && sudo cpio -id) >/dev/null 2>/dev/null ||
  failure "" "Installation of bash failed."
rpm2cpio sh-utils-2.0-5.i386.rpm | (cd $INSTALLDIR &&
    sudo cpio -id bin/sleep bin/nice) >/dev/null 2>/dev/null ||
  failure "" "Installation of sh-utils failed."
rpm2cpio fileutils-4.0-21.i386.rpm |
    (cd $INSTALLDIR && sudo cpio -id bin/cp) >/dev/null 2>/dev/null ||
  failure "" "Installation of fileutils failed."
if test -n "$VVINSTALLMAINTAINER"; then
echo -ne "OK\nInstalling strace... "
rpm2cpio strace-4.2-1.i386.rpm |
    (cd $INSTALLDIR; sudo cpio -id usr/bin/strace) >/dev/null 2>/dev/null ||
  failure "" "Installation of strace failed."
sudo mv $INSTALLDIR/usr/bin/strace $INSTALLDIR/bin/strace
echo "00000f5: 746d702f6c642d76766c6e78" | sudo xxd -r - $INSTALLDIR/bin/strace
fi
echo -ne "OK\nFixing directory access modes... "
sudo find $INSTALLDIR -type d -exec chmod 755 {} \; ||
  failure "" "Couldn't correct access mode of directories."
echo -ne "OK\nAdding symbolic link for libstdc++... "
(cd $INSTALLDIR/usr/lib; \
    sudo ln -s libstdc++-2-libc6.1-1-2.9.0.so libstdc++-libc6.1-1.so.2) ||
  failure "" "Couldn't create symbolic link."
if test -n "$VVINSTALLMAINTAINER"; then
  echo -ne "OK\nAdding symbolic links... "
  DIRNOW=`pwd`
  cd $INSTALLDIR/lib
  (for f in `find . -type l ! -name '*.so'`; do \
    DEST=`echo $f | sed -e 's%\./%%'`; \
    SRC=`echo $DEST | sed -e 's%\.so\.[0-9]*$%.so%'`; \
    test -L $SRC || sudo ln -s $DEST $SRC || exit 1; \
  done) || failure "" "Couldn't create symbolic links."
  cd $DIRNOW
fi
echo OK
# Not needed.
sudo rm $INSTALLDIR/usr/lib/libstdc++.so.2.7.2.8

# Fix the jdk to use these libraries.
echo "Fixing $INSTALLDIR/jdk1.2.2/bin/.java_wrapper"
ID="$INSTALLDIR"
cat $INSTALLDIR/jdk1.2.2/bin/.java_wrapper | \
  sed -e 's%ld="[^$]*\$%ld="'$ID'/lib:'$ID'/usr/lib:'$ID'/usr/X11R6/lib:$%' \
  -e 's%.*exec [^$]*\$%    export PATH="'$ID'/bin:'$ID'/jdk1.2.2/bin"; \
  exec '$INSTALLDIR'/lib/ld-linux.so.2 $%' > /tmp/.java_wrapper.new.$$
sudo install --mode=755 --owner=root --group=0 \
  /tmp/.java_wrapper.new.$$ $INSTALLDIR/jdk1.2.2/bin/.java_wrapper
rm /tmp/.java_wrapper.new.$$

# Fix the dynamic linker of the executables
echo "Replacing dynamic linker in executables with /tmp/ld-vvlnx.so.2."
for f in `file $INSTALLDIR/bin/* $INSTALLDIR/usr/bin/* |
    grep 'ELF.*dynamically linked' | cut -d: -f1`; do
  echo "00000f5: 746d702f6c642d76766c6e78" | sudo xxd -r - $f
done
# /tmp/ld-vvlnx.so.2 -> $INSTALLDIR/lib/ld-linux.so.2
(cd /tmp; ln -sf $INSTALLDIR/lib/ld-linux.so.2 ld-vvlnx.so.2) ||
  failure "" "Could not add symbolic link /tmp/ld-vvlnx.so.2."
# Fix all occurances of '/bin/sh' in the libraries.
echo "Replacing all references to '/bin/sh' in library with '/tmp/vv'."
echo "00e3ffa: 746d702f7676" | sudo xxd -r - $INSTALLDIR/lib/libc-2.1.3.so
echo "00e6588: 746d702f7676" | sudo xxd -r - $INSTALLDIR/lib/libc-2.1.3.so
echo "00e6596: 746d702f7676" | sudo xxd -r - $INSTALLDIR/lib/libc-2.1.3.so
echo "00e796b: 746d702f7676" | sudo xxd -r - $INSTALLDIR/lib/libc-2.1.3.so
echo "00e81c8: 746d702f7676" | sudo xxd -r - $INSTALLDIR/lib/libc-2.1.3.so
echo "00e8779: 746d702f7676" | sudo xxd -r - $INSTALLDIR/lib/libc-2.1.3.so
# /tmp/vv -> $INSTALLDIR/bin/sh
(cd /tmp; ln -sf $INSTALLDIR/bin/sh vv) ||
  (echo "Could not add symbolic link /tmp/vv.  Aborting."; exit 1) || exit 1

echo "(Re)installing ViaVoice rpms..."
# Using sudo here, just in case it changes HOME (it shouldn't, normally).
sudo echo  "vvinstalling" >> $HOME/vvisinstalling ||
  failure "" "Cannot create $HOME/vvisinstalling."
sudo rpm -ivh $VIAVOICERPMDIR/ViaVoice_runtime-3.0-1.2.i386.rpm ||
  failure "" "Problem with (re)installation of ViaVoice_runtime."
sudo rpm -ivh $VIAVOICERPMDIR/ViaVoice_TTS_rtk-5.1-1.2.i386.rpm ||
  failure "" "Problem with (re)installation of ViaVoice_TTS_rtk."
sudo rpm -ivh $VIAVOICERPMDIR/ViaVoice_Dictation-1.0-1.0.i386.rpm ||
  failure "" "Problem with (re)installation of ViaVoice_Dictation."
sudo rm -f $HOME/vvisinstalling
sudo cp -rf $VIAVOICERPMDIR/dict.lic.ila.txt /usr/doc/ViaVoice ||
  failure "" "Problem with installation of license file!"
# Total license agreement covers these others
sudo rm -f /usr/doc/ViaVoice/rt.lic.txt
sudo rm -f /usr/doc/ViaVoice/dict.lic.txt

if test -e /proc/asound; then
  echo "Changing the default recording buffer size in audoss.so."
  echo "000156a: "$ALSASIZECODE"00 ff7f" | sudo xxd -r - /usr/lib/ViaVoice/bin/audoss.so
  echo "0001660: "$ALSASIZECODE"00 ff7f" | sudo xxd -r - /usr/lib/ViaVoice/bin/audoss.so
fi

# Binary patch the ViaVoice binaries to use the dynamic linker of glibc-2.1.3.
echo "Replacing dynamic linker in ViaVoice executables with /tmp/ld-vvlnx.so.2."
for f in `file /usr/lib/ViaVoice/bin/* |
          grep 'ELF.*dynamically linked' | cut -d: -f1`; do
  if test "$f" != "/usr/lib/ViaVoice/bin/rtinstconfig"; then
    echo "00000f5: 746d702f6c642d76766c6e78" | sudo xxd -r - $f
  fi
done

echo -n "Fixing shell magic at the start of ViaVoice scripts... "
# All /usr/bin/vv* scripts have a license added as header,
# invalidating the magic "#! /" at the start.
for f in /usr/bin/vvsetenv /usr/bin/vvstart* \
         /usr/lib/ViaVoice/bin/vvsetuser; do
  # Is it a script, but the magic is not on the first line?
  if grep '^#! */' $f >/dev/null &&
     test `grep -n '^#! */' $f | cut -d: -f 1` != "1"; then
    NAME=`echo "$f" | sed 's%.*/%%'`
    echo "#! /bin/bash" > /tmp/$NAME.new.$$ || failure "" "Cannot create /tmp/$NAME.new.$$"
    grep -v '^#! */' $f >> /tmp/$NAME.new.$$ || failure "" "grep failed."
    chmod 755 /tmp/$NAME.new.$$ || failure "" "chmod failed."
    sudo mv /tmp/$NAME.new.$$ $f || failure "" "mv failed."
  fi
done

# Change '/bin/sh' into '/tmp/vv'
echo -ne "OK\nReplacing all references to '/bin/sh' "
echo "in ViaVoice executables with '/tmp/vv'."
echo "00d83bd: 746d702f7676" | sudo xxd -r - /usr/lib/ViaVoice/bin/engine
echo "0010274: 746d702f7676" | sudo xxd -r - /usr/lib/ViaVoice/bin/trnscr11
echo "0010274: 746d702f7676" | sudo xxd -r - /usr/lib/ViaVoice/bin/trnscrnq

# Fix vvsetenv.
echo -n "Fixing /usr/bin/vvsetenv... "
cp /usr/bin/vvsetenv /tmp/vvsetenv.new.$$ || failure "" "cp failed."
echo -e "\n#------------------------------------------" >> /tmp/vvsetenv.new.$$
echo "# Things below are added by vvinstall $VERSION" >> /tmp/vvsetenv.new.$$
echo 'export PATH="'$INSTALLDIR'/jdk1.2.2/bin:$PATH"' >> /tmp/vvsetenv.new.$$
echo '(cd /tmp; ln -sf '$INSTALLDIR'/lib/ld-linux.so.2 ld-vvlnx.so.2) ||' \
  >> /tmp/vvsetenv.new.$$
echo -n '(echo "Could not add symbolic link /tmp/ld-vvlnx.so.2.  Aborting.";' \
  >> /tmp/vvsetenv.new.$$
echo ' sleep 4; exit 1) || exit 1' >> /tmp/vvsetenv.new.$$
echo -n '(cd /tmp; ln -sf '$INSTALLDIR'/bin/sh vv) ||' >> /tmp/vvsetenv.new.$$
echo ' (echo "Could not add symbolic link /tmp/vv.  Aborting.";' \
  >> /tmp/vvsetenv.new.$$
echo ' sleep 4; exit 1) || exit 1' >> /tmp/vvsetenv.new.$$
chmod 755 /tmp/vvsetenv.new.$$ || failure "" "chmod failed."
sudo mv /tmp/vvsetenv.new.$$ /usr/bin/vvsetenv ||
  failure "" "mv failed."
echo OK

# Fix vvsetuser.
echo -n "Fixing /usr/lib/ViaVoice/bin/vvsetuser... "
(cat /usr/lib/ViaVoice/bin/vvsetuser | sed -e 's%.*\$SPCH_BIN%\
# PATH and LD_LIBRARY_PATH added by vvinstall version '$VERSION'\
PATH="'$INSTALLDIR'/bin" LD_LIBRARY_PATH="'$INSTALLDIR'/lib:'\
$INSTALLDIR'/usr/lib:/usr/lib" $SPCH_BIN%' > /tmp/vvsetuser.new.$$ &&
chmod 755 /tmp/vvsetuser.new.$$) || (echo "FAILURE"; exit 1) || exit 1
sudo mv /tmp/vvsetuser.new.$$ /usr/lib/ViaVoice/bin/vvsetuser ||
  failure "" "mv failed."
echo "OK"

#------------------------------------------------------------------------------
# Finish.

echo
echo "Installation in \"$INSTALLDIR\" successful."
echo
echo -n ">>> Now run "
if test -d ~/viavoice; then
  echo "'vvstartaudiosetup' or 'vvstartenrollment' (vvstartuserguru)"
  echo ">>> or 'vvstartdictation' as usual."
  echo ">>> See /usr/doc/ViaVoice/rt.readme.txt for more info."
else
  echo "'vvstartuserguru'."
  echo ">>> Don't forget to read /usr/doc/ViaVoice/rt.readme.txt!"
fi

