#!/bin/bash

. /etc/rc.d/init.d/functions

is_ok_www () {
  [ -d "$1" -o -h "$1" ] || return 1
  [ "`stat -c %N $1 | grep /var/www/html`" ] && return 1
  [ "`find $1/ -type f -print -quit`" ] || return 1
  return 0
}

stop () {
  [ "`grep /var/www/html /etc/mtab`" ] || return
  gprintf "Unmounting web directories: "
  for mpoint in `grep bind /etc/mtab | grep -Eo /var/www/html/[^\ ]+`; do
    umount $mpoint
  done
  success "Unmounting web directories: "; echo
}

start () {
  gprintf "Mounting web directories: "
  for www in `cd /home && echo */www`; do
    if is_ok_www "/home/$www"; then
      mpoint=/var/www/html/${www%/www}
      [ ! -d $mpoint ] && mkdir $mpoint
      mount --bind /home/$www $mpoint
    fi
  done
  success "Mounting web directories: "; echo
}

case "$1" in
  start|restart|reload)
    stop
    start
    exit 0
    ;;
  stop)
    stop
    exit 0
    ;;
  status)
    [ "`grep /var/www/html /etc/mtab`" ] && echo "mounted" || echo "not mounted"
    ;;
  *)
    gprintf "Usage: %s {start|stop|restart|reload|status}\n" $0
    exit 1
    ;;
esac

