#! /bin/csh

# Basic sanity checks: Inform the curious user what is this script for
if ( $#argv == 0 ) goto TOOL_NOT_SPECIFIED
if ( "$1" == "-?" ) goto WRONG_ARGS
if ( "$1" == "--?" ) goto WRONG_ARGS
if ( "$1" == "-h" ) goto WRONG_ARGS
if ( "$1" == "--h" ) goto WRONG_ARGS
if ( "$1" == "-help" ) goto WRONG_ARGS
if ( "$1" == "--help" ) goto WRONG_ARGS

# Get the location of the script
# Use a dedicated variable because variable modifiers (:h) are not allowed on $0
set COMMAND_NAME = ( $0 )
pushd "$COMMAND_NAME:h" > /dev/null
# Use pwd instead of dirname to avoid .. and . in path; we need normalized path to parse the instance name and id
set SCRIPT_LOCATION = ( `pwd` )
popd > /dev/null

# Check the input parameters
set NODE_NAME = ( $1 )
if ( ".$NODE_NAME" == "." ) goto TOOL_NOT_SPECIFIED

set STARTUP_FILE = ( $2 )
if ( ".$STARTUP_FILE" == "." ) then
  set STARTUP_FILE = "$SCRIPT_LOCATION/startup.properties"
  set PARAMETERS = ( $argv[2-] )
else
  set PARAMETERS = ( $argv[3-] )
endif

if ( ! ( -r $STARTUP_FILE ) ) goto STARTUP_FILE_NOT_READABLE

set INSTANCE_NUMBER = ( `echo $SCRIPT_LOCATION | sed -e 's^.*\([0-9][0-9]\)/j2ee/cluster/bootstrap/scripts^\1^'` )
set INSTANCE_NAME = ( `echo $SCRIPT_LOCATION | sed -e 's^.*/\([A-Z]*[0-9][0-9]\)/j2ee/cluster/bootstrap/scripts^\1^'` )

# Get the profile path
set PROFILE = (`$SCRIPT_LOCATION/../../../../exe/sapcontrol -nr $INSTANCE_NUMBER -prot NI_HTTP -function ParameterValue SAPPROFILE_IN_EFFECT`)
if ("$PROFILE[4]" != "OK" ) goto SAPSTARTSRV_ERROR
set PROFILE = ( $PROFILE[5] )
if ( ! ( -r $PROFILE ) ) goto PROFILE_ERROR

# Launch the tool via JSF
$SCRIPT_LOCATION/../../../../exe/jstart -launch -nodename=$NODE_NAME -file=$STARTUP_FILE pf=$PROFILE $PARAMETERS
set JSTART_EXITCODE = ( $status )
#Display the output
set OUTPUT_FILE = ( $SCRIPT_LOCATION/../../../../work/jvm_$NODE_NAME.out )
if ( -r $OUTPUT_FILE ) cat $OUTPUT_FILE
if ( $JSTART_EXITCODE ) echo "ERROR: JStart exit code [$JSTART_EXITCODE], see details in log file [dev_$NODE_NAME]"

goto END

### ERROR CASES ###

# ERROR - the script parameters are totaly wrong
WRONG_ARGS:
set JSTART_EXITCODE = ( 10 )
echo "$0 : This helper script is not designed to be run directly"
goto END

# ERROR - startup file not found
STARTUP_FILE_NOT_READABLE:
set JSTART_EXITCODE = ( 11 )
echo "FATAL: Cannot read startup file: [$STARTUP_FILE]"
goto END

# ERROR - no tool specified
TOOL_NOT_SPECIFIED:
set JSTART_EXITCODE = ( 13 )
echo "FATAL: No tool specified for launch"
goto END

# ERROR - the instance can not be parsed
INSTANCE_ERROR:
set JSTART_EXITCODE = ( 14 )
echo "FATAL: Instance not found"
goto END

# ERROR - the profile does not exist
PROFILE_ERROR:
set JSTART_EXITCODE = ( 15 )
echo "FATAL: Cannot read profile: [$PROFILE]"
goto END

# ERROR - the sapstartsrv is not started
SAPSTARTSRV_ERROR:
set JSTART_EXITCODE = ( 16 )
echo "FATAL: SAPSTART service for instance [$INSTANCE_NAME] is not started"
goto END

END:
exit $JSTART_EXITCODE
# This newline must remain