#!/bin/sh
# Author: Blake, Kuo-Lien Huang
# License: GPL
# Description: 
#   a wrapper of drbl-host-rm, drbl-user-rm

if [ -f /usr/bin/tput ]; then
  NORMAL=`tput sgr0 2> /dev/null`
  BOLD=`tput bold 2> /dev/null`
else
  NORMAL=""
  BOLD=""
fi

drbl_user_rm=`which drbl-user-rm`
drbl_host_rm=`which drbl-host-rm`
if [ "$drbl_user_rm" = "" ]; then drbl_user_rm="/opt/drbl/sbin/drbl-user-rm"; fi
if [ "$drbl_host_rm" = "" ]; then drbl_host_rm="/opt/drbl/sbin/drbl-host-rm"; fi

if [ ! -f $drbl_user_rm -o ! -f $drbl_host_rm ]; then
  echo "DRBL installation incomplete.. Abort.."
  exit
fi

usage() {
  echo "Usage:"
  echo "  ${BOLD}$0 DEST${NORMAL}"
  echo
  echo "Example:"
  echo "  If you would like to remove the file ./ABCD on users' public_html/hw1.html,"
  echo "  use the command:"
  echo "  ${BOLD}# $0 [:ALL_USERS:]/public_html/hw1.html${NORMAL}"
  echo
  echo "  Use ${BOLD}[:ALL_HOSTS:]/${NORMAL} instead of ${BOLD}[:ALL_USERS:]/${NORMAL} means" 
  echo "  removing from all DRBL clients"
  echo
  echo "  Use ${BOLD}[:GROUP_XXX:]/${NORMAL} instead of ${BOLD}[:ALL_USERS:]/${NORMAL} means"
  echo "  only the users of the group XXX choosen to remove"
  exit 0
}

#if [ $# -lt 2 ]; then usage; fi

group=""
cmd=""
cmdopt=""
dest=$1

if [ "$(echo "$dest" | grep -e "^\[:ALL_USERS:\]/")" != "" ]; then
  cmd="$drbl_user_rm";
  dest=${dest/[:ALL_USERS:/}; dest=${dest/]\//}

elif [ "$(echo "$dest" | grep -e "^\[:ALL_HOSTS:\]/")" != "" ]; then
  cmd="$drbl_host_rm"
  dest=${dest/[:ALL_HOSTS:/}; dest=${dest/]\//} 

elif [ "$(echo "$dest" | grep -e "^\[:GROUP_[^:]*:\]/")" != "" ]; then
  cmd="$drbl_user_rm"
  cmdopt=$dest; cmdopt=${cmdopt%]*}; cmdopt=${cmdopt/[:GROUP_/}
  cmdopt=${cmdopt%:*}
  dest=${dest/[:GROUP_$cmdopt:/}; dest=${dest/]\//}

elif [ "$(echo "$dest" | grep -e "^\[:[0-9]*\.[0-9]*\.[0-9]*\.[0-9]*\:]")" ]; then
  host=${dest%]*}
  host=${host/[/}
  dest=${dest/$host/}
  dest=${dest/[/}
  dest=${dest/]/}
  if [ ! -e /var/lib/diskless/default/$host ]; then 
    echo "No such client..Abort"; exit; 
  fi
  if [ "$dest" != "" ]; then
    rm -rf /var/lib/diskless/default/$host/$dest
  fi
  exit
fi

if [ "$dest" = "" -o "$cmd" = "" ]; then usage; fi
if [ "$cmdopt" != "" ]; then cmdopt="-g $cmdopt"; fi

echo "$cmd $cmdopt $dest"
eval "$cmd $cmdopt $dest"
