#!/bin/sh
# vim: et sw=2 ts=2
# dist: public

# change this to the root of your asss installation
ASSSHOME=$HOME/src/asss

# start of stuff not to change

# possible exit values. these should match those in defs.h
E_SHUTDOWN=0
E_RECYCLE=1
E_GENERAL=2
E_OOM=3
E_MODCONF=4
E_MODLOAD=5
E_CHROOT=6

if [ "$1" ]; then
  ZONEDIR=$ASSSHOME/$1
else
  ZONEDIR=$ASSSHOME
fi

SCRIPTLOG=$ZONEDIR/log/wrapper.log
log ()
{
  echo "*** $*"
  echo "`date '+%Y.%m.%d %H:%M:%S'`: $*" >> $SCRIPTLOG
}

if [ ! -d $ZONEDIR ]; then
  echo "Directory '$ZONEDIR' not found."
  exit 1
fi

cd $ZONEDIR

# check sanity
if [ ! -e conf/modules.conf ]; then
  echo "This directory doesn't look like a valid zone directory."
  exit 1
fi

# figure out which binary to run
if [ -e bin/asss ]; then
  ASSS=bin/asss
else
  ASSS=$ASSSHOME/bin/asss
fi

# figure out if this zone is set up for chrooting
if [ \( -e lib/ld-linux.so.2 \) -a \( -u $ASSS \) ]; then
  echo "*** chroot enabled"
  CHROOT=--chroot
fi

CONTINUE=true

while $CONTINUE; do

  log "asss started"

  $ASSS $CHROOT
  EXIT=$?

  [ -e core ] && mv core core-`date +%m%d%H%M`

  SLEEP=3

  if [ $EXIT -eq $E_SHUTDOWN ]; then
    MSG="shutdown"
    CONTINUE=false
  elif [ $EXIT -eq $E_RECYCLE ]; then
    MSG="recycle, restarting"
  elif [ $EXIT -eq $E_GENERAL ]; then
    MSG="unknown general error"
    CONTINUE=false
  elif [ $EXIT -eq $E_OOM ]; then
    MSG="out of memory, restarting"
  elif [ $EXIT -eq $E_MODCONF ]; then
    MSG="error in modules.conf"
    CONTINUE=false
  elif [ $EXIT -eq $E_MODLOAD ]; then
    MSG="error loading modules"
    CONTINUE=false
  elif [ $EXIT -eq $E_CHROOT ]; then
    MSG="error in chroot"
    CONTINUE=false
  elif [ $EXIT -gt 128 ]; then
    MSG="due to signal `expr $EXIT - 128`, restarting"
  else
    MSG="UNKNOWN EXIT CODE: $EXIT"
    CONTINUE=false
  fi

  log "asss exited: $MSG"

  sleep $SLEEP

done

