#!/bin/sh
# Author: Blake, Kuo-Lien Huang
# License: GPL
# Description:

usage() {
  echo "Usage: $0 server_name [on|off]"
  echo "       $0 [--list|-l] list the client services and its status"
  #echo "       $0 [--dialog]  use dialog to turn on/off client services"
  exit 0
}

drblhost="/var/lib/diskless/default/"
name=$1
op=$2

# must be root
ID=`id -u`
if [ "$ID" != "0" ]; then
  echo "You must be root to use this script."
  echo "Use sudo to enable it for users."
  exit 1
fi

#if [ "$name" = "" ]; then usage; fi
if [ "$name" = "" ]; then
#if [ "$name" = "--dialog" ]; then
  TMP=`mktemp /tmp/client-service.XXXXXX`
  DIA=dialog
  SERVICELIST=""
  for service in `ls $drblhost/root/etc/rc2.d/`; do
    s=${service:0:1}
	n=${service:3}
	case $s in
	 "S") SERVICELIST="$SERVICELIST $n $n on" ;;
	 "K") SERVICELIST="$SERVICELIST $n $n off" ;;
	 *) continue ;; 
	esac
  done

  $DIA --backtitle "drbl-client-switch" \
  --title "Turn on/off client services" \
  --checklist "" 20 60 15 $SERVICELIST 2> $TMP
  boot_services=$(cat $TMP | sed -e "s/\"//g")
  if [ "$boot_services" = "" ]; then exit 0; fi

  for service in `ls $drblhost/root/etc/rc2.d/`; do
    s=${service:0:1}
	n=${service:3}
    ##
    found=0
    for boot_service in $boot_services; do
      if [ "$boot_service" = "$n" ]; then found=1; break; fi
    done
    ##
	case $s in
	 "S") [ $found -eq 0 ] && $0 $n off ;;
     "K") [ $found -eq 1 ] && $0 $n on ;;
	 *) continue ;; 
	esac
  done   

  rm -f $TMP
  exit 0
fi

if [ "$name" = "--list" -o "$name" = "-l" ]; then
  for service in `ls $drblhost/root/etc/rc2.d/`; do
    s=${service:0:1}
	n=${service:3}
    # format the output
	case $s in
	 "S") echo "[*]$n" ;;
	 "K") echo "[ ]$n" ;;
	 *) continue ;; 
	esac
  done
  exit 0
fi

if [ "$op" = "" ]; then usage; fi

for host in `ls $drblhost`; do
  if [ "$host" = "." -o "$host" = ".." ]; then continue; fi

    case "$op" in
      "on")
        if [ -f $drblhost/$host/etc/rc2.d/K*$name ]; then
          rcK=`ls $drblhost/$host/etc/rc2.d/K*$name`
          rcK=${rcK/$drblhost\/$host\/etc\/rc2.d\//}
          rcS=${rcK/K/S}
		  mv $drblhost/$host/etc/rc2.d/$rcK $drblhost/$host/etc/rc2.d/$rcS
		fi
        ;;
      "off")
        if [ -f $drblhost/$host/etc/rc2.d/S*$name ]; then
          rcS=`ls $drblhost/$host/etc/rc2.d/S*$name`
          rcS=${rcS/$drblhost\/$host\/etc\/rc2.d\//}
          rcK=${rcS/S/K}
		  mv $drblhost/$host/etc/rc2.d/$rcS $drblhost/$host/etc/rc2.d/$rcK
        fi
        ;;
      *)
        usage
        ;;
    esac

done
