#!/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

$GEMSTONE/bin/topaz -l << EOF
output pushnew $GEMSTONE_LOGDIR/maintenance_gem.log
set user DataCurator pass $GEMSTONE_CURATOR_PASS gems $GEMSTONE_NAME

display oops
iferror stack

login

run
"record gems pid in the pid file"
| file |
(GsFile isServerDirectory: '$GEMSTONE_DATADIR') ifFalse: [ ^nil ].
file := GsFile openWriteOnServer: '$GEMSTONE_DATADIR/maintenance_gem.pid'.
file nextPutAll: (System gemVersionReport at: 'processId') printString.
file cr.
file close.
%

run
| count |
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. Assuming default 60 second STN_GEM_ABORT_TIMEOUT, wake 
  up at 30 second intervals."
[ 
  [ true ] whileTrue: [ (Delay forSeconds: 30) wait ].
] forkAt: Processor lowestPriority.

count := 0.
[true] whileTrue: [ | expired |
  expired := 0.
  GsFile gciLogServer: DateAndTime now printString.
  GsFile gciLogServer: 'Unregistering...'.
  System beginTransaction.
  WADispatcher default entryPoints do: [:app |
	expired := expired + (app handlers unregisterExpiredPersistentHandlersFor: app).
  ].
  System commitTransaction.
  GsFile gciLogServer: '...Expired: ', expired printString, ' sessions.'.
  ((count \\\\ 120) = 0) 
    ifTrue: [ 
      GsFile gciLogServer: DateAndTime now printString.
      GsFile gciLogServer: 'Starting markForCollect.'.
      [
        SystemRepository markForCollection
      ] on: Error 
        do: [:ex | 
          ((ex gsNumber == 3020) _or: [ex gsNumber == 3006])
            ifTrue: [GsFile gciLogServer: ex description]
            ifFalse: [ex pass ]
        ].
      GsFile gciLogServer: DateAndTime now printString.
      GsFile gciLogServer: '...finished markForCollect.'.
    ].
  (Delay forSeconds: 60) wait.
  count := count + 1.
].
%

EOF
