#!/bin/sh
#                 Sun Public License Notice
# 
# The contents of this file are subject to the Sun Public License
# Version 1.0 (the "License"). You may not use this file except in
# compliance with the License. A copy of the License is available at
# http://www.sun.com/
# 
# The Original Code is NetBeans. The Initial Developer of the Original
# Code is Sun Microsystems, Inc. Portions Copyright 1997-2002 Sun
# Microsystems, Inc. All Rights Reserved.

# -----------------------------------------------------
# Run with -help for usage.
# Normally, editing this script should not be required.
# -----------------------------------------------------

# use $JDK_HOME or $NB_JDK_HOME or the -jdkhome switch, do not edit this here
# (see below for info on .runide_defaults.sh)
jdkhome=""

# append on command line or ide.cfg, with -J prefix on each
jreflags=""

PRG=$0

#
# resolve symlinks
#

while [ -h "$PRG" ]; do
    ls=`ls -ld "$PRG"`
    link=`expr "$ls" : '^.*-> \(.*\)$' 2>/dev/null`
    if expr "$link" : '^/' 2> /dev/null >/dev/null; then
	PRG="$link"
    else
	PRG="`dirname "$PRG"`/$link"
    fi
done

progdir=`dirname "$PRG"`
progname=`basename "$0"`

idehome="$progdir/.."

# absolutize idehome

oldpwd=`pwd` ; cd "${idehome}"; idehome=`pwd`; cd "${oldpwd}"; unset oldpwd

# calculate branding to brand userdir with
defaults="$idehome/bin/.runide_defaults.sh"
if [ -r "$idehome/lib/branding" ]; then
    branding=`cat "$idehome/lib/branding"`
    if [ -r "$idehome/bin/.runide_defaults_$branding.sh" ]; then
        defaults="$idehome/bin/.runide_defaults_$branding.sh"
    fi
fi
# This script should set the var userdir at the least:
# (another likely option would be $jdkhome, see #18628)
. "$defaults"

jargs=${jreflags}
jargs="$jargs -Dnetbeans.home=\"$idehome\""
jargs="$jargs -Djava.security.policy=\"$idehome/bin/ide.policy\""

args=""

prefixcp=""
postfixcp=""

updater_class=org.netbeans.updater.UpdaterFrame
openfile_class=org.netbeans.modules.openfile.Main
ide_class_option=

#
# defaults
#

# if JDK_HOME is set it overrides ${JAVA_PATH}

if [ ! -z "$JDK_HOME" -a -z "$jdkhome" ] ; then
    jdkhome="$JDK_HOME"
fi

# if JAVA_PATH is set it is used if necessary

if [ ! -z "$JAVA_PATH" -a -z "$jdkhome" ] ; then
    jdkhome="$JAVA_PATH"
fi

#
# parse arguments
#

parse_args() {
while [ $# -gt 0 ] ; do
#    echo "Processing arg: '$1'"
    case "$1" in
        -h|-help) cat <<EOF
Usage: $0 {options} arguments

Options can be

   -h -help
        shows usage
   -?
        help on more parameters (not interpreted by launcher)
   -jdkhome <path>
        path to JDK (could also be just JRE but some modules may not work!)
   -userdir <path>
        specifies user settings directory (${userdir} by default)
   -J<jvm_options>
        passes <jvm_option> to JVM
Opening files (requires utilities.jar to be enabled & Open File server on):
   -open <filename>
        open a file in the IDE (either uses existing IDE or launches new)
   -host <hostname>
        host to connect to; default localhost
   -port <portnumber>
        port to connect to; default 7318
Classpath options (normally you should NOT use these except to support -ui):
   -cp:p <classpath>
        prepends <classpath> to IDE's classpath
   -cp:a <classpath>
        appends <classpath> to IDE's classpath

All other options and arguments are passed to the IDE, so try -? for more.
Any options found in $HOME/ide.cfg or else $idehome/bin/ide.cfg
are treated as defaults (may be overridden).
See documentation for details.
EOF
exit 1
;;
        -jdkhome) shift; if [ $# -gt 0 ] ; then jdkhome=$1; fi;;
        -userdir) shift; if [ $# -gt 0 ] ; then userdir=$1; fi;;
        -open) shift; if [ $# -gt 0 ] ; then openfile=$1; fi;;
        -port) shift; if [ $# -gt 0 ] ; then port=$1; fi;;
        -host) shift; if [ $# -gt 0 ] ; then host=$1; fi;;
        # For compatibility only:
        -mainclass) shift; if [ $# -gt 0 ] ; then ide_class_option=-Dnetbeans.mainclass=$1; fi;;
        -cp|-cp:a)
            shift;
            if [ $# -gt 0 ] ; then
                if [ ! -z "$postfixcp" ] ; then postfixcp="$postfixcp:" ; fi
                postfixcp=$postfixcp$1;
            fi
            ;;
        
        -cp:p)
            shift;
            if [ $# -gt 0 ] ; then
                if [ ! -z "$prefixcp" ] ; then prefixcp="$prefixcp:" ; fi
                prefixcp=$prefixcp$1;
            fi
            ;;
        
        -J*) jopt=`expr "$1" : '-J\(.*\)'`; jargs="$jargs \"$jopt\"";;
        *) args="$args \"$1\"" ;;
    esac
    shift
done
} # parse_args()

# Process any ./ide.cfg or ~/ide.cfg.
# Note that there is no quoting scheme for these files.
if [ -r "${HOME}/ide.cfg" ]; then
    parse_args `cat "${HOME}"/ide.cfg`
elif [ -r "${progdir}/ide.cfg" ]; then
    parse_args `cat "${progdir}"/ide.cfg`
# else leave as is
fi

if [ -f /usr/j2se/opt/javahelp/lib/jhall.jar ]; then
    # See http://www.netbeans.org/issues/show_bug.cgi?id=22455
    jhjar="`echo ${idehome}/modules/autoload/ext/jh-*.jar`"
    parse_args "-J-Xbootclasspath/p:${jhjar}"
fi

# Process arguments given on the command line.
parse_args "$@"

#
# check JDK
#

if [ -z "$jdkhome" ] ; then
    echo "Cannot find JDK. Please set the JDK_HOME environment variable to point"
    echo "to your JDK installation directory, or use the -jdkhome switch"
    echo ""
    exit 1
fi

if [ ! -x "${jdkhome}/bin/java" ] ; then
    echo "Cannot find JDK at ${jdkhome}. Please set the JDK_HOME"
    echo "environment variable to point to your JDK installation directory,"
    echo "or use the -jdkhome switch"
    echo ""
    exit 1
fi

#
# open file?
#

if [ ! -z "$openfile" -a -f "${idehome}/modules/utilities.jar" ] ; then
    args=""
    if [ ! -z "$host" ] ; then
        args="$args -host $host"
    fi
    if [ ! -z "$port" ] ; then
        args="$args -port $port"
    fi
    eval "\"$jdkhome/bin/java\"" -classpath "\"${idehome}/modules/utilities.jar\"" $openfile_class $args "\"$openfile\""
    rc=$?
    
    if [ $rc -eq 0 -o $rc -eq 1 ] ; then
        exit 0
    else
        jargs="-Dnetbeans.openfile=\"$openfile\" $jargs"
    fi
fi

#
# check userdir
#

if [ ! -z "$userdir" ] ; then
    jargs="-Dnetbeans.user=\"${userdir}\" $jargs"
fi

#
# increase file descriptor's limit, on Solaris it's set to 64, too small for
# fastjavac
#

ulimit -n 1024

append_jars_to_cp() {
    dir="$1"
    for ex in jar zip ; do
        if [ "`echo "${dir}"/*.$ex`" != "${dir}/*.$ex" ] ; then
            for x in "${dir}"/*.$ex ; do
                if [ ! -z "$cp" ] ; then cp="$cp:" ; fi
                cp="$cp$x"
            done
        fi
    done
}

build_cp() {
    base="$1"
    append_jars_to_cp "${base}/lib/ext"
    append_jars_to_cp "${base}/lib/ext/locale"
}

do_run_updater() {
    eval "\"$jdkhome/bin/java\"" -classpath "\"${updatercp}\"" $jargs $updater_class
}

look_for_pre_runs() {
    base="$1"
    dir="${base}/update/download"
    if [ -f "${dir}/install_later.xml" -a "`echo "${dir}"/*.nbm`" != "${dir}/*.nbm" ] ; then
        run_updater=yes
    fi
}

look_for_post_runs() {
    base="$1"
    dir="${base}/update/download"
    if [ \! -f "${dir}/install_later.xml" -a "`echo "${dir}"/*.nbm`" != "${dir}/*.nbm" ] ; then
        run_updater=yes
    fi
}

#
# dump the OS env variables into a temp file
#

nbenvfile="/tmp/nbenv.$$"

# attempt to delete a leftover from crashed instance which happened to have the
# same PID

rm -f ${nbenvfile}

# if ${nbenvfile} already exists there is a possibility that it is a leftover
# after another instance of this script crashed and the owner of the file can
# be another user (PIDs are reused).  In such a case keep appending 'X' to the
# filename until we find an unused name

while [ -f "$nbenvfile" ]
do
    nbenvfile=${nbenvfile}X
done

# #30621: handle embedded newlines in values, if possible.
if [ -r /proc/self/environ ]
then
    cat /proc/self/environ > "$nbenvfile"
    nbenvnullsep=true
# XXX works, but spends extra 350msec on a Solaris box I saw; probably too obscure to be worth it:
#elif perl -e 'foreach (keys %ENV) {print "$_=$ENV{$_}\0"}' > "$nbenvfile" 2> /dev/null
#then
#    nbenvnullsep=true
elif [ -x /usr/bin/env ] ; then
    /usr/bin/env > "$nbenvfile"
    nbenvnullsep=false
else
    echo "" > "$nbenvfile"
    nbenvnullsep=false
fi

# Note that Bash calls this even if you stop the command with Ctrl-C;
# Solaris' /bin/sh does not - but both call it on normal exit.
trap "rm -f '$nbenvfile'" EXIT

#
# main loop
#

# clear to prevent loop from ending
restart="yes"
first_time_starting="yes"

while [ "$restart" ] ; do

    #
    # build CLASSPATH
    #
    
    cp=""
    updatercp=""
    
    build_cp "${idehome}"
    
    if [ -f "${idehome}/lib/updater.jar" ] ; then
        updatercp="${idehome}/lib/updater.jar"
    fi

    # JDK tools
    
    for ex in jar zip ; do
        # XXX does this still work if ${jdkhome} contains spaces?
        if [ "`echo "${jdkhome}"/lib/*.$ex`" != "${jdkhome}/lib/*.$ex" ] ;then
            for x in "${jdkhome}"/lib/*.$ex ; do
                if [ ! -z "$cp" ] ; then cp="$cp:" ; fi
                cp="${cp}$x"
            done
        fi
    done

    # user-specified prefix and postfix CLASSPATH
    
    if [ ! -z "${prefixcp}" ] ; then
        cp="${prefixcp}:$cp"
    fi
    
    if [ ! -z "${postfixcp}" ] ; then
        cp="$cp:${postfixcp}"
    fi


    # prepend IDE's classpath to updater's classpath
    # (just xml-apis.jar and one XML parser would suffice)
    if [ ! -z "$updatercp" ] ; then
        updatercp=${cp}:${updatercp}
    else
        updatercp=${cp}
    fi

    # First check for pre-run updates.
    if [ "$first_time_starting" ] ; then
        run_updater=""
        look_for_pre_runs "$idehome"
        look_for_pre_runs "$userdir"
        if [ "$run_updater" ] ; then do_run_updater ; fi
        # Do not check this after a restart, it makes no sense.
        first_time_starting=""
    fi
    
    #
    # let's go
    #

    if [ ! -z "$openfile" -a -f "${idehome}/modules/utilities.jar" ] ; then
        openfile_prop="-Dnetbeans.openfile=\"$openfile\""
        openfile=""
    fi
    
    eval ${_NB_PROFILE_CMD} "\"${jdkhome}/bin/java\"" -Djdk.home="\"${jdkhome}\"" -classpath "\"$cp\"" \
        -Dnetbeans.osenv="${nbenvfile}" -Dnetbeans.osenv.nullsep=${nbenvnullsep} \
        ${openfile_prop} \
        $jargs $ide_class_option org.netbeans.Main $args

    # If we should update anything, do it and restart IDE.
    run_updater=""
    look_for_post_runs "$idehome"
    look_for_post_runs "$userdir"
    if [ "$run_updater" ] ; then
        do_run_updater
        restart="yes"
    else
        restart=""
        # will fall thru loop and exit
    fi

done

# and we exit.
