#!/bin/bash

if [ -s $GEMSTONE/seaside/etc/gemstone.secret ]; then
    . $GEMSTONE/seaside/etc/gemstone.secret
else
    echo 'Missing password file $GEMSTONE/seaside/etc/gemstone.secret'
    exit 1
fi

# Requires a port number as a parameter
if [ "a$1" = "a" ]; then
        echo 'Missing argument <server port number>'
        exit 1
fi

cat << EOF | nohup $GEMSTONE/bin/topaz -l -T50000 2>&1 >> $GEMSTONE_LOGDIR/FastCGI_server-${1}.log &

set user DataCurator pass $GEMSTONE_CURATOR_PASS gems $GEMSTONE_NAME

display oops
iferror where

login

run
"record gems pid in the pid file"
| file |
(GsFile isServerDirectory: '$GEMSTONE_DATADIR') ifFalse: [ ^nil ].
file := GsFile openWriteOnServer: '$GEMSTONE_DATADIR/FastCGI_server-${1}.pid'.
file nextPutAll: (System gemVersionReport at: 'processId') printString.
file cr.
file close.
(ObjectLogEntry 
  info: 'FastCGI: startup' 
  object: 
    'pid: ', (System gemVersionReport at: 'processId') printString, ' ',
    'port: ', $1 printString) addToLog.
%
System commitTransaction 
    ifFalse: [ 
      System abortTransaction.
      nil error: 'Could not commit ObjectLog entry' ].
run

GsProcess usingNativeCode not
  ifTrue: [
    "Enable remote Breakpoing handling"
    Breakpoint trappable: true.
    GemToGemAnnouncement installStaticHandler.
    System commitTransaction ifFalse: [ nil error: 'Could not commit for GemToGemSignaling' ].
  ].

System transactionMode: #manualBegin.

Exception 
  installStaticException: 
    [:ex :cat :num :args |
      "Run the abort in a lowPriority process, since we must acquire the
       transactionMutex."
      [
        SeasidePlatformSupport transactionMutex 
          critical: [ 
            SeasidePlatformSupport doAbortTransaction ].
        System enableSignaledAbortError.
      ] forkAt: Processor lowestPriority.
    ]
  category: GemStoneError
  number: 6009
  subtype: nil.
System enableSignaledAbortError.
"This thread is needed to handle the SigAbort exception, when the primary
 thread is blocked on an accept. Assuming default 60 second 
 STN_GEM_ABORT_TIMEOUT, wake up at 30 second intervals."
[ 
  [ true ] whileTrue: [ (Delay forSeconds: 30) wait ].
] forkAt: Processor lowestPriority.


GsFile gciLogServer: 'FastCGI Server started on port ', $1 printString.

FSSeasideHandler startUp: $1.
"does not return"
%
run
GemToGemAnnouncement uninstallStaticHandler.
System beginTransaction.
(ObjectLogEntry
  fatal: 'FastCGI: topaz exit'
  object:
    'port: ', $1 printString, ' ',
    'pid: ', (System gemVersionReport at: 'processId') printString) addToLog.
System commitTransaction.
%
EOF

