#!/bin/sh

# Written By Fredrik Hbinette <hubbe@hubbe.net>
# All rights reserved. No warrenties, use at your own risk.
# This source is distributed under the GNU GENERAL PUBLIC LICENCE,
# see the file "COPYING" for more information.

# $Id: plugger-oohelper,v 1.9 2004/07/20 15:26:58 hubbe Exp $

""":"
OIFS="${IFS-}"

ooprefix=''

for prefix in s o
do
  prog=${prefix}office
  IFS=:
  for p in $PATH
  do
    IFS="$OIFS"
    if [ -f "$p/$prog" ]; then
      ooprefix="$prefix"
      oolocation="$p/$prog"
      ooprogdir="$p"
      while [ -h "$oolocation" ];
      do
        base="`basename "$oolocation"`"
        lnk="`ls -l "$oolocation" | sed "s@.*$base -> @@g"`"
        case "$lnk" in
           /*) oolocation="$lnk" ;;
           *) oolocation="$ooprogdir/$lnk" ;;
        esac
        ooprogdir="`dirname "$oolocation"`"
      done
      if [ -f "$ooprogdir/python.sh" ]; then
         shift
         exec "$ooprogdir/python.sh" "$0" "$oolocation" "$@"
      fi
      if [ -f "$ooprogdir/../lib/openoffice/program/python.sh" ]; then
         shift
         exec "$ooprogdir/../lib/openoffice/program/python.sh" "$0" "$oolocation" "$@"
      fi
    fi
  done
done

if [ "x${ooprefix}" == "xs" ]; then
  exec s$1 -n "$@" "$file" >/dev/null
fi

if [ "x${ooprefix}" == "xo" ]; then
  exec oo$1 -n "$@" "$file" >/dev/null
fi

echo "Failed to find OpenOffice python script utility!!"
exit 10
"""

import uno
import os
import sys
import time

from com.sun.star.beans import PropertyValue

# get the uno component context from the PyUNO runtime
localContext = uno.getComponentContext()

# create the UnoUrlResolver 
resolver = localContext.ServiceManager.createInstanceWithContext(
				"com.sun.star.bridge.UnoUrlResolver", localContext )

# connect to the running office

x=0
while 1:
    try:
        ctx = resolver.resolve( "uno:socket,host=localhost,port=2002;urp;StarOffice.ComponentContext" )
	break
    except:
        if x == 0:
            os.system('"%s" -quickstart  "-accept=socket,host=localhost,port=2002;urp;" &' % sys.argv[1])
        elif x < 300:
            time.sleep(0.2)
        else:
            raise
        x=x+1
        

smgr = ctx.ServiceManager

# get the central desktop object
desktop = smgr.createInstanceWithContext( "com.sun.star.frame.Desktop",ctx)
cwd = uno.systemPathToFileUrl( os.getcwd() )
fileUrl = uno.absolutize( cwd, uno.systemPathToFileUrl(os.environ["file"]) )
inProps = (
	PropertyValue( "Hidden" , 0 , False, 0 ), 
	PropertyValue( "ReadOnly" , 0 , True, 0 ), 
	PropertyValue( "OpenNewView" , 0 , True, 0 ), 
)

url=os.environ.get("url","")
if url:
   inProps=inProps+( PropertyValue( "URL" , 0 , url, 0 ), )

mt=os.environ.get("mime-type",None)
if mt and mt != "application/octet-stream":
   inProps=inProps+( PropertyValue( "MediaType" , 0 , mt, 0 ), ) 


doc = desktop.loadComponentFromURL( fileUrl , "_blank", 0, inProps )

# Flush
ctx.ServiceManager
