#!/bin/sh
#
# Wrapper script for openoffice
#
# (C) Peter 'Nidd' Novodvorsky, 2001,2002
# (C) Martin 'empty' Quinson, 2002.
#     Modifications by Chris Halls
#     Modifications by Lucien Saviot

# 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; if not, write to the Free Software                  
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA      

if [ -f /etc/openoffice/settings.conf ]; then
  . /etc/openoffice/settings.conf
else
  OOVERSION="OpenOffice.org 1.1.2"
  OOPATH="/opt/OpenOffice.org1.12" 
fi

##
## Source system configuration file
##
[ -r /etc/openoffice/openoffice.conf ] && . /etc/openoffice/openoffice.conf

###
### Get user settings directory from ~/.sversionrc and echo directory name to stdout
### get_settings_dir <Version>
### return: 0 - directory found, 
###         1 - ~/.sversionrc non existent
###         2 - entry exists in ~/.sversionrc but directory not found
###         3 - ~/.sversionrc exists but no entry found
###         4 - entry found but soffice link is broken (upgrade from openoffice.org1.1)
get_settings_dir()
{
  [ -r ~/.sversionrc ] || exit 1
  # warning, .sversionrc is DOS encoded so strip ^M
  settings_dir="`tr -d  '\r' < ~/.sversionrc | sed -n "/^$1=/s%^$1=file://\(.*\)$%\1%p"`"
  echo "$settings_dir"
  [ -n "$settings_dir" ] || return 3
  [ -d "$settings_dir" ] || return 2
  [ -x "`readlink "$settings_dir/soffice"`" ] || return 4
}

###
### Get settings directory and handle return codes
### check_settings_dir <Version>
### OOHOME is set to settings directory
###
### return: 0 - directory found
###         1 - ~/.sversionrc non existent
###         3 - ~/.sversionrc exists but no entry found
check_settings_dir()
{
  OOHOME="`get_settings_dir "$OOVERSION"`" ; check_oo_ret=$?
  if [ $check_oo_ret -eq 2 ] ; then
    # .sversionrc contains a version yet the directory does not exist
    echo "I'm confused because I can't find OpenOffice's user files." >&2
    echo "Your ~/.sversionrc file tells they should be under $OOHOME," >&2
    echo "but they are not. Please fix the situation manually." >&2
    echo "You may want to edit ~/.sversionrc to indicate where is OO" >&2
    echo "installed, or remove it if you did remove your installation" >&2
    echo "directory manually (you bad one)." >&2
    exit 1
  elif [ $check_oo_ret -eq 4 ] ; then
    if readlink "$OOHOME/soffice" | grep -q "/usr/lib/openoffice1.1/program/soffice"; then
      echo "Adjusting links to openoffice binaries..."
      ln -sf $OOPATH/program/soffice "$OOHOME/soffice"
      ln -sf $OOPATH/program/spadmin "$OOHOME/soffice"
      ln -sf $OOPATH/program/setup "$OOHOME/setup"
      check_oo_ret=0
    fi
  fi
  return $check_oo_ret
}

###
### Change locale for OOo 1.1
### change_locale <new locale>
#change_locale()
#{
#  TMPFILE=`mktemp -t oooLocale.XXXXXXXXXX` && {
#    cat > $TMPFILE <<EOF
#<?xml version="1.0" encoding="UTF-8"?>
#<oor:node xmlns:oor="http://openoffice.org/2001/registry" xmlns:xs="http://www.w3.org/2001/XMLSchema" oor:name="Setup" oor:package="org.openoffice">
# <node oor:name="L10N">
#  <prop oor:name="ooLocale" oor:type="xs:string">
#   <value>$1</value>
#  </prop>
# </node>
#</oor:node>
#EOF
#    ooconfigimport $TMPFILE > /dev/null
#
#    rm -f $TMPFILE
#  }
#
#}

### get_upgrade_versions <path to instdb.ins to search>
### Print a list to stdout of versions that this version will upgrade from
### These are extracted from the UpdateFor key in instdb.ins
### when this was written, the versions returned were:
### "OpenOffice.org 1.0.3" "OpenOffice.org 1.0.2" "OpenOffice.org 1.0.1" "OpenOffice.org 1.0" "OpenOffice.org 1.1"
get_upgrade_versions()
{
  sed -n '
  /[[:space:]]*UpdateFor[[:space:]]*=[[:space:]]*/ {
    # Remove UpdateFor = prefix as matched above
    s///
    
    # Remove trailing semicolon
    s/;[[:space:]]*$//

    # Convert semicolon separators to " "
    s/;/" "/g
    p
  }
  ' < $1
}

### can_upgrade
### Return 0 if an older upgradeable version of the user config is found
can_upgrade()
{
  # get list of supported old versions
  eval set -e -- `get_upgrade_versions $OOPATH/program/instdb.ins`

  while [ $# -gt 0 ]; do
    if oldhome="`get_settings_dir "$1"`" && [ -d "$oldhome" ] ; then
      echo "Previous version found: $1"
      return 0
    fi
    shift
  done
  return 1
}

### get_lock_info <path-to-OOo-install>
### return 0 if .lock file is not found
### otherwise set LOCK_USER, LOCK_HOST and LOCK_FILE
get_lock_info()
{
  LOCK_FILE="$1/.lock"
  if [ -f "$LOCK_FILE" ]; then
    LOCK_USER="$(sed -n '/^User=/ s///p' < "$LOCK_FILE")"
    LOCK_USER="$(sed -n '/^Host=/ s///p' < "$LOCK_FILE")"
    return 1
  fi
  return 0
}

# clean dangerous symlinks, taken from ooo-wrapper
# http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=245561
clean_symlinks()
{
  for L in work user/work; do
    if [ -L "$oldhome/$L" ]; then
      if ! rm "$oldhome/$L"; then
	echo "openoffice.org:  You have a dangerous link in $oldhome/$L, aborting install" >&2
	echo "Please remove this file and try again." >&2
	exit 1
      fi
    fi
  done

}

## OOo does not start if /proc is not mounted, so check for it
if [ ! -f /proc/version ]; then
  echo "openoffice.org:  You must have a working /proc filesystem to use openoffice." >&2
  echo "Please mount /proc and try again" >&2
  exit 1
fi

##
## where does OO live for this user ? Set OOHOME.
##
check_settings_dir "$OOVERSION"

##
## Add known Debian fonts locations to search path for Woody backport
##
## NOTE: This is *not* used in package versions that use libfontconfig, ie
## unstable/testing  This is only for the Woody backport, where libfontconfig is
## not available.
##

# Default font path.  This is used if SAL_FONTPATH_USER is not defined.
DEBOO_FONTPATH="/usr/lib/X11/fonts/misc/;/usr/lib/X11/fonts/cyrillic/;\
/usr/lib/X11/fonts/100dpi/:unscaled;/usr/lib/X11/fonts/75dpi/:unscaled;\
/usr/lib/X11/fonts/Type1/;/usr/lib/X11/fonts/CID;/usr/lib/X11/fonts/Speedo/;\
/usr/lib/X11/fonts/100dpi/;/usr/lib/X11/fonts/75dpi/;\
/var/lib/defoma/x-ttcidfont-conf.d/dirs/TrueType;\
/usr/share/fonts/truetype;\
/usr/share/fonts/truetype/kochi;\
/usr/share/fonts/truetype/larabie-straight;\
/usr/share/fonts/truetype/larabie-deco;\
/usr/share/fonts/truetype/larabie-uncommon;\
"

SAL_FONTPATH_PRIVATE=${SAL_FONTPATH_USER:-"$DEBOO_FONTPATH"}
export SAL_FONTPATH_PRIVATE

## search LOCALE
if [ -n "$LC_ALL" ]; then
  LOCALE="$LC_ALL"
  # OOo doesn't understand LC_ALL, so set LANG
  LANG="$LC_ALL"
elif [ -n "$LANG" ]; then
  LOCALE="$LANG"
elif [ -n "$LC_MESSAGES" ]; then
  LOCALE="$LC_MESSAGES"
  LANG="$LC_MESSAGES"
else
  LOCALE="en_US"
fi

# Set locale to en_US if locale is C
if [ "x$LOCALE" = "xC" ] ; then LOCALE="en_US"; fi

# Change _ to - and remove part after '@' character
LOCALEOO=`echo $LOCALE | sed 's/_/-/;s/@.*//'`

##
## install OO for this user if needed
##
if [ -z "$OOHOME" ] ; then
  if ! get_lock_info "$OOHOME"; then
    # We need to upgrade but OOo is already running
    echo "Lockfile $LOCK_FILE found" >&2
    echo "OpenOffice.org is already running as user $LOCK_USER on host $LOCK_HOST" >&2
    echo "Please shut down all instances of soffice.bin and OOo quickstarter and try again">&2
    exit 1
  fi

  if [ -e /etc/openoffice/autoresponse-workstation.conf ] && \
    grep -q DESTINATIONPATH /etc/openoffice/autoresponse-workstation.conf ; then

    if can_upgrade; then
      clean_symlinks
      TMPFILE=`mktemp -t oooAutoreponse.XXXXXXXXXX` || exit 1
      sed -e "s#^DESTINATIONPATH=.*#DESTINATIONPATH=$oldhome#" \
        < /etc/openoffice/autoresponse-workstation.conf > $TMPFILE
	
      echo "upgrading openoffice.org user configuration..."

      if ! $OOPATH/program/setup -nogui -R:$TMPFILE ; then
        echo "setup failed (code $?).. abort" >&2
        rm -f $TMPFILE
        exit 1
      fi

      rm -f $TMPFILE

    else
      # first install
      responsefile=/etc/openoffice/autoresponse-workstation.conf

      OOHOME=`grep DESTINATIONPATH /etc/openoffice/autoresponse-workstation.conf | \
             sed -e 's/DESTINATIONPATH=//' -e "s|<home>|$HOME|"`

      if [ -d "$OOHOME" ]; then
        echo "openoffice.org:  You have no entry for $OOVERSION in ~/.sversionrc, " >&2
        echo "yet the directory $OOHOME exists."  >&2
        echo "Please remove $OOHOME and try again." >&2
        exit 1
      fi

      echo "running openoffice.org setup..."

      if ! $OOPATH/program/setup -nogui -R:/etc/openoffice/autoresponse-workstation.conf ; then
        echo "setup failed (code $?).. abort" >&2
        exit 1
      else 
        # remove kde menu (Blake,2004/08/16)
        rm -rf "$HOME/.kde/share/applnk/$OOVERSION"
      fi
    fi

    # test that installation exists
    if ! check_settings_dir "$OOVERSION"; then
      echo "Setup did not complete properly - cannot find an entry in ~/.sversionrc" >&2
      exit 1
    fi
    
    echo "Setup complete.  Running openoffice.org..."

else
    echo "openoffice.org: Damnit! I can't find OpenOffice's conffiles." >&2
    echo "Did you delete or modify /etc/openoffice/autoresponse.conf manually?" >&2
    echo "To restore the files you should purge openoffice.org and reinstall," >&2
    echo "or use 'dpkg --force-confmiss' to reinstall the openoffice.org .deb" >&2
    exit 1
  fi
fi

##
## If no file is specified on the command line, which application to start?  
## The wrapper can be called from several links in /usr/bin
##
if [ $# = 0 ]; then
  case `basename $0` in
    oocalc) set -- -calc;;
    oodraw) set -- -draw;;
    ooimpress) set -- -impress;;
    oomath) set -- -math;;
    oowriter) set -- -writer;;
    ooweb) set -- -web;;
    oomaster) set -- -global;;
    oofromtemplate) set -- slot:5500;;
  esac
fi

#if ! get_lock_info "$OOHOME"; then
#  # OOo is already running
#  echo "OpenOffice.org lockfile found ($LOCK_FILE)"
#  echo "Using existing OpenOffice.org"
#else
#  ## Change locale of OOo
#  change_locale "$LOCALEOO"
#fi

##
## That's it. Launch the beast (with the given args)
##
LANG=$LOCALE
export LANG
exec "$OOPATH/program/soffice" "$@"

