#!/bin/bash
#
### BEGIN INIT INFO
# Provides:          mysql-socketmount-admin
# Required-Start:    $remote_fs $syslog mysql-admin
# Required-Stop:     $remote_fs $syslog mysql-admin
# Should-Start:      $network $time
# Should-Stop:       $network $time
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Mount admin mysql into chroots
# Description:       Mount admin mysql into chroots
### END INIT INFO
#

. /lib/lsb/init-functions

bindmount() {

    srcdir=$1
    dstdir=$2

    if (cat /proc/mounts |grep $dstdir >/dev/null); then
	log_warning_msg "skipping $dstdir (already mounted)"
    else
	log_progress_msg "$dstdir"
	mount --bind -o defaults,noexec,nosuid $srcdir $dstdir
    fi
}

CFGDIR=/chroot/admin/etc/mysql
SCFG=$CFGDIR/mysocketmount.cnf

if ! [ -d "$CFGDIR" ]; then log_failure_msg "$CFGDIR not found!" "mysql-socketmount-admin"; exit 3; fi
if ! [ -f "$SCFG" ]; then log_failure_msg "$SCFG not found!" "mysql-socketmount-admin"; exit 3; fi

source "$SCFG"

if ! [ -d "$SOCKETDIR" ]; then log_warning_msg "Source socket dir not found!" "mysql-socketmount-admin"; exit 0; fi
if ! [ -n "$DESTDIRS" ]; then log_warning_msg "No destination dir defined!" "mysql-socketmount-admin"; exit 0; fi


case "${1:-''}" in
  'start')
	log_daemon_msg "Mounting MySQL socket to chroot jails" "mysql-socketmount-admin"
	for destdir in $DESTDIRS; do
	    if [ -d $destdir ]; then
		bindmount $SOCKETDIR $destdir
	    fi
	done
	log_end_msg 0
	;;

  'stop')
	log_daemon_msg "Unmounting MySQL sockets from chroot jails" "mysql-socketmount-admin"
	for destdir in $DESTDIRS; do
	    if [ -d $destdir ]; then
		umount $destdir
	    fi
	done
	log_end_msg 0
	;;
  *)
	echo "Usage: /etc/init.d/mysql-socketmount-admin {start|stop}"
	exit 1
	;;
esac

