#!/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
#     Modifications by Rene Engelhard

# 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      

# this string should be exactly as in ~/.sversionrc
OOVERSION="OpenOffice.org 1.1.3"
VER=

##
## Source system configuration file
##
[ -r /etc/openoffice${VER}/openoffice.conf ] && . /etc/openoffice${VER}/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 /usr/lib/openoffice${VER}/program/soffice "$OOHOME/soffice"
      ln -sf /usr/lib/openoffice${VER}/program/spadmin "$OOHOME/soffice"
      ln -sf /usr/lib/openoffice${VER}/program/setup "$OOHOME/setup"
      check_oo_ret=0
    fi
  fi
  return $check_oo_ret
}

### 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 /usr/lib/openoffice${VER}/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${VER}/autoresponse.conf ] && \
    grep -q DESTINATIONPATH /etc/openoffice${VER}/autoresponse.conf ; then
    echo "OpenOffice.org for Debian - see /usr/share/doc/openoffice.org${VER}/README.Debian.gz"

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

      if ! /usr/lib/openoffice${VER}/program/setup -nogui -R:$TMPFILE ; then
        echo "setup failed (code $?).. abort" >&2
        echo "---- Please read /usr/share/doc/openoffice.org${VER}/README.Debian.gz for known problems -----" >&2
        rm -f $TMPFILE
        exit 1
      fi

      rm -f $TMPFILE

    else
      # first install
      responsefile=/etc/openoffice${VER}/autoresponse.conf

      OOHOME=`grep DESTINATIONPATH /etc/openoffice${VER}/autoresponse.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 ! /usr/lib/openoffice${VER}/program/setup -nogui -R:/etc/openoffice${VER}/autoresponse.conf ; then
        echo "setup failed (code $?).. abort" >&2
        echo "---- Please read /usr/share/doc/openoffice.org${VER}/README.Debian.gz for known problems -----" >&2
        exit 1
      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${VER}) set -- -calc;;
    oodraw${VER}) set -- -draw;;
    ooimpress${VER}) set -- -impress;;
    oomath${VER}) set -- -math;;
    oowriter${VER}) set -- -writer;;
    ooweb${VER}) set -- -web;;
    oomaster${VER}) set -- -global;;
    oofromtemplate${VER}) 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
  LD_LIBRARY_PATH="/usr/lib/openoffice/program/:$LD_LIBRARY_PATH" \
  	/usr/lib/openoffice/program/setofficelang.bin -f "$LOCALEOO"
fi

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

## Changelog
# 2004/10/14 rene
#   * run setofficelang.bin with -
# 2004/08/12 rene
#   * Version 1.1.3
# 2004/07/20 rene
#   * use setofficelang.bin instead of importing locale config with
#     ooconfigimport
# 2004/07/07 rene
#   * stop overwriting LC_CTYPE
# 2004/06/18 rene
#   * Version 1.1.2
# 2004/04/28 halls
#   * clean work and user/work symlinks from older versions before upgrade
#     since they are dangerous
# 2004/04/16 halls
#   * detect .lock file and don't try to run setup if found
# 2004/03/03 rene
#    * Version 1.1.1
# 2004/02/16 halls
#    * Check for /proc
# 2004/01/20 rene
#    * Version 1.1.1a
# 2003/12/16 halls
#   * Send error messages to stderr
#   * Also adjust links immediately after upgrade 
#     (needed for woody backport 1.1beta2->1.1.0 transition)
#   * Pass -nogui to setup command line
# 2003/10/08 halls
#   * Override LC_CTYPE with LANG to workaround limitation of OOo locales
# 2003/08/15 halls
#   * Move the destination of the softlinks if created by 1.1 packaging
#   * Call /usr/lib/openoffice/program/soffice directly instead of via the link
# 2003/07/22 halls
#   * Remove 1.0.x code
#   * Strip part of locale after '@', since OOo doesn't understand it
#   * Detect upgradeable versions
#   * Check that user directory exists after running setup
# 2003/07/04 halls
#   * Update font paths
#   * Version is 1.1.0 for rc1
# 2003/06/12 halls
#   * Need to use SAL_FONTPATH_PRIVATE for fontpath now
# 2003/04/24 halls
#   * Packaging for 1.1
#   * Remove Session manager workaround
#   * Disable migration from older version for now
#   * Disable langpack selection for now
#   * Add ${VER} suffix to directory name openoffice.org->openoffice.org1.1 etc.
# 2003/04/01 halls
#   * Version 1.0.3
# 2003/02/03 halls
#   * Check for nonexistent ooLocale every run
# 2003/01/09 halls
#   * Version 1.0.2
# 12/15 saviot
#   * Change ooLocale at startup in Setup.xml
#   <ooLocale cfg:type="string"/> doesn't work for help.
# 12/03 challs
#   * Add Debian font paths to user font path
# 11/14 saviot
#   * correct handling of UI language
#   * don't change Linguistic.xml after first startup(#168780)
#   * TODO: provide better defaults on first startup
# 10/03 challs
#   * Fix use with LC_ALL
# 07/10 challs
#   * use 1.0.1 directory and improve error checking
# 07/02 challs
#   * use readlink in /proc/PID/exe to get
#     real session manager name
# 06/12 challs
#   * merge into main package
#   * change $@ to "$@"
#   * source configuration file: 
#       /etc/openoffice/openoffice.conf
# 06/12 mquinson
#   * strace only when DEBUG is set to yes
#   * readd the $@ to pass the args to soffice
# 06/06 mquinson
#   * Make sure the OLDLOCALE is never empty
#   * handle the case where the locale is C
# vi: sw=2 

