#!/bin/bash

DRBL_SCRIPT_PATH="${DRBL_SCRIPT_PATH:-/opt/drbl/}"

. $DRBL_SCRIPT_PATH/sbin/drbl-conf-functions
. $DRBL_SCRIPT_PATH/conf/drbl-ocs.conf
. $DRBL_SCRIPT_PATH/sbin/ocs-functions

#

start() {
  # image name is like: sanboot.aoe-0-0-for-00-50-56-02-01-02
  for i in $sanboot_img_dir/*.aoe-*; do
    shelf_no="$(echo $i | grep -Eo "aoe-[[:digit:]]+-[[:digit:]]+-for-.*" | awk -F'-' '{print $2}')"
    slot_no="$(echo $i | grep -Eo "aoe-[[:digit:]]+-[[:digit:]]+-for-.*" | awk -F'-' '{print $3}')"
    mac_add="$(echo $i | grep -Eo "aoe-[[:digit:]]+-[[:digit:]]+-for-.*" | sed -e 's/^aoe-.*-for-//g')"
    mac_name_cfg_for_pxe="01-${mac_add}"
    echo "AoE image found: $i"
    echo "Checking if vblade service for aoe:e${shelf_no}.${slot_no} is running..."
    ps_status="$(ps -ef | grep -Ew "vblade[[:space:]]+${shelf_no}[[:space:]]+${slot_no}" | grep -v "grep")"
    if [ -n "$ps_status" ]; then
      echo "vblade service for aoe.e${shelf_no}.${slot_no} is running. Skip this one"
      continue
    fi
    # Todo: find the right eth port instead of running on all. This can be done by parsing the dhcpd.conf if MAC addresses are used in dhcpd.conf.
    eth_ports="$(get-all-nic-ip --drbl-client-eth-port)"
    for j in $eth_ports; do
      echo "Starting virtual blade exports for ${i##*/} by:"
      vbladed ${shelf_no} ${slot_no} $j $i
    done
    # Set pxelinux config file
    cp -f $PXE_CONF_DEF $PXELINUX_DIR/$mac_name_cfg_for_pxe
    hide_reveal_pxe_img "AoE-client" reveal $PXELINUX_DIR/$mac_name_cfg_for_pxe
    set-default-pxe-img -i "AoE-client" -c $PXELINUX_DIR/$mac_name_cfg_for_pxe
    # Change the line: append aoe:e0.0
    drbl-tune-pxecfg-block AoE-client "^([[:space:]]*)append aoe:.*" "\$1append aoe:e${shelf_no}.${slot_no}" $PXELINUX_DIR/$mac_name_cfg_for_pxe
  done

  # Use gpxelinux.0 instead of pxelinux.0 in dhcpd.conf
  if ! grep -iEq '^[[:space:]]*filename[[:space:]]*=[[:space:]]*[\"]*gpxelinux.0[\"]*' $DHCPDCONF_DIR/dhcpd.conf; then
    echo "Use gpxelinux.0 instead of pxelinux.0 in dhcpd.conf..."
    perl -pi -e 's|(^filename[[:space:]]*=[[:space:]]*.*pxelinux.0.*)|#$1|g' $DHCPDCONF_DIR/dhcpd.conf
    perl -pi -e 's|(^[#]*[[:space:]]*filename[[:space:]]*=[[:space:]]*.*gpxelinux.0.*)|filename = "gpxelinux.0";|g' $DHCPDCONF_DIR/dhcpd.conf
    # Restart dhcpd service, since different distributions have different names
    for serv_st in dhcpd dhcp3-server; do
      [ -e "/etc/init.d/$serv_st" ] && /etc/init.d/$serv_st restart
    done
  fi
} # end of start

stop() {
  pkill -9 vblade
}

restart() {
  stop
  sleep 2
  start
}

status() {
  ps -efw | grep -iE "vblade [[:digit:]]+ [[:digit:]]+"
}

#
case $1 in
  start)   start;;
  stop)    stop;;
  restart) restart;;
  status)  status;;
  *)       echo "Usage: $0 {start|stop|restart|status}"
	   exit 1 
esac
