#!/bin/sh

# Check that we're on a system that has been configured already
if [ ! -s /etc/sysconfig/cluster ]; then
   echo "Error: /etc/sysconfig/cluster does not exist or is empty!"
   exit 1
fi

. /etc/sysconfig/cluster

config_base() {
   # Create server config file
   echo "${MASTER_NODE_NAME}" >/var/spool/torque/server
}

config_mom() {
   # Create server_priv/config config file
   echo "\$clienthost ${MASTER_NODE_NAME}" >/var/spool/torque/mom_priv/config
   echo "\$logevent 0xff" >>/var/spool/torque/mom_priv/config
}

config_server() {
   # Create the nodes file
   if [ -s "/var/spool/torque/server_priv/nodes" ]; then
      rm -f "/var/spool/torque/server_priv/nodes"
   fi
   if [ ${HOSTNAME_PADDING} ]; then
      seq_opt="-w"
   fi
   for n in `seq $seq_opt ${COMPUTE_NODE_COUNT}`; do
      echo "${COMPUTE_NODE_NAME_PREFIX}$n np=2" >>/var/spool/torque/server_priv/nodes
   done

   # Check for the existence of the pbs_server database and if it does
   # not exist create a new one.  Otherwise skip this step and leave
   # the old one intact.
   SERVERDB=/var/spool/torque/server_priv/serverdb
   if [ ! -s "${SERVERDB}" ]; then
      # Attempt to start the server for the first time which when
      # terminated will create an empty database.
      /usr/sbin/pbs_server -t create

      # Create a simple default queue
      /usr/bin/qmgr </usr/share/doc/torque-server/torque-default.queue >/dev/null

      # Terminate the server so that it will write the newly created
      # database.
      /usr/bin/qterm -t quick
   else
      echo "${SERVERDB} exists.  Skipping initial database creation."
   fi
}


case "$1" in
   all)
      # Check for the required rpm before configuring packages
      if [ `rpm -q torque &>/dev/null; echo $?` = '0' ]; then
         config_base
      fi
      if [ `rpm -q torque-server &>/dev/null; echo $?` = '0' ]; then
         config_server
      fi
      if [ `rpm -q torque-mom &>/dev/null; echo $?` = '0' ]; then
         config_mom
      fi
      ;;
   base)
      config_base
      ;;
   mom)
      config_mom
      ;;
   server)
      config_server
      ;;
   *)
      echo "Usage:  aspen-config-torque TYPE"
      echo "   all    - Auto-configure all torque related packages installed on the"
      echo "            current system"
      echo "   base   - Auto-configure the base system"
      echo "   mom    - Auto-configure the mom daemon"
      echo "   server - Auto-configure the server"
      exit 1
esac

exit 0
