#!/bin/bash

########
# 安裝 openPBS / torque
########
if [ ! -e torque-2.3.6.tar.gz ]; then
  wget http://www.clusterresources.com/downloads/torque/torque-2.3.6.tar.gz
  tar zxvf torque-2.3.6.tar.gz
  cd torque-2.3.6/
  ./configure
  sudo make
  sudo make install
  # to make sure libtorque.so.2 is updated
  # or there will be an error message:
  #
  # pbs_mom: error while loading shared libraries: libtorque.so.2: cannot open shared object file: 
  #          No such file or directory
  #
  sudo ldconfig
  # create init.d scripts for torque
  sudo cp contrib/init.d/debian.pbs_mom    /etc/init.d/pbs_mom
  sudo cp contrib/init.d/debian.pbs_sched  /etc/init.d/pbs_sched
  sudo cp contrib/init.d/debian.pbs_server /etc/init.d/pbs_server
fi

sudo cat /etc/dhcp3/dhcpd.conf | grep "host .* {" | awk '{ print $2 }' > nodes
sudo mv nodes /var/spool/torque/server_priv/nodes
sudo pbs_server -t create
cat > torque_conf << EOF
create queue batch
set queue batch queue_type = Execution
set queue batch started = True
set queue batch enabled = True
set server default_queue = batch
set server resources_default.nodes = 1
set server scheduling = True
EOF
sudo qmgr < torque_conf
cat >> config << EOF
\$pbsserver    $(hostname)
\$logevent     255
EOF
sudo mv config /var/spool/torque/mom_priv/jobs/config
# terminate pbs_server and pbs_schedule
sudo qterm -t quick
sudo /etc/init.d/pbs_sched stop
# re-deploy DRBL
sudo /opt/drbl/sbin/drblpush -c /etc/drbl/drblpush.conf
# copy torque related configuration files for pbs_mom
sudo /opt/drbl/sbin/drbl-cp-host /var/spool/torque/server_priv/nodes /var/spool/torque/server_priv/nodes
sudo /opt/drbl/sbin/drbl-cp-host /var/spool/torque/mom_priv/jobs/config /var/spool/torque/mom_priv/jobs/config
sudo /opt/drbl/sbin/drbl-cp-host /var/spool/torque/pbs_environment /var/spool/torque/pbs_environment
sudo /opt/drbl/sbin/drbl-cp-host /var/spool/torque/server_name /var/spool/torque/server_name
# enable pbs_mom service for DRBL Clients
sudo /opt/drbl/sbin/drbl-client-service pbs_mom on
# enable pbs_sched and pbs_server services for DRBL Server
sudo update-rc.d pbs_sched defaults
sudo update-rc.d pbs_server defaults
# restart pbs_sched and pbs_server
sudo /etc/init.d/pbs_sched start
sudo /etc/init.d/pbs_server start
# start pbs_mom
sudo /opt/drbl/sbin/drbl-doit /etc/init.d/pbs_mom start
