#!/bin/sh
# Script to stop a jail
# Args $1 = jail-dir
#######################################################################

# Source our functions
PROGDIR="`pbreg get /PC-BSD/TheWarden/ProgDir`"

if [ -z "${PROGDIR}" ]
then
   echo "PROGDIR unset! Is The Warden installed properly?"
   exit 155
fi

# Source our variables
. ${PROGDIR}/conf/warden.conf

IP="${1}"
if [ "${2}" = "FAST" ]
then
  FAST="Y"
fi

if [ -z "${IP}" ]
then
  echo "ERROR: No jail specified to delete!"
  exit 5
fi

if [ -z "${JDIR}" ]
then
  echo "ERROR: JDIR is unset!!!!"
  exit 5
fi

if [ ! -d "${JDIR}/${IP}" ]
then
  echo "ERROR: No jail located at $JDIR/$IP"
  exit 5
fi


HOST="`cat ${JDIR}/${IP}/etc/.wardenhost`"

# Make sure the jail is running
jls | grep ${IP} >/dev/null 2>/dev/null
if [ "$?" != "0" ]
then
  echo "ERROR: Jail is not running!"
  exit 6
fi

# End of error checking, now shutdown this jail
##################################################################

echo -e "Stopping the jail...\c"

# Get the JailID for this jail
JID="`jls | grep ${IP} | tr -s " " ":" | cut -d ":" -f 2`"

echo -e ".\c"


# Check if we need to remove the IP alias from this jail
ifconfig $NIC | grep ${IP} >/dev/null 2>/dev/null
if [ "$?" = "0" ]
then
  ifconfig $NIC inet -alias ${IP}
  echo -e ".\c"
fi

# Create our shutdown script and run it in the jail
echo "#!/bin/sh
sh /etc/rc.shutdown
umount -f /dev" > "${JDIR}/${IP}/.shutdown"
chmod 755 "${JDIR}/${IP}/.shutdown"
chroot "${JDIR}/${IP}" "/.shutdown" >/dev/null 2>/dev/null
rm "${JDIR}/${IP}/.shutdown"

echo -e ".\c"

# Skip the time consuming portion if we are shutting down
if [ "$FAST" != "Y" ]
then

# We asked nicely, so now kill the jail for sure
killall -j ${JID} -TERM 2>/dev/null
sleep 1
killall -j ${JID} -KILL 2>/dev/null

echo -e ".\c"

# Check if we need to unmount the devfs in jail
mount | grep "${JDIR}/${IP}/dev" >/dev/null 2>/dev/null
if [ "$?" = "0" ]
then
  # Setup a 60 second timer to try and umount devfs, since takes a bit
  SEC="0"
  while
   i=1
  do
   sleep 2

   # Try to unmount dev
   umount -f "${JDIR}/${IP}/dev" 2>/dev/null
   if [ "$?" = "0" ]
   then
      break
   fi

   SEC="`expr $SEC + 2`"
   echo -e ".\c"

   if [ ${SEC} -gt 60 ]
   then
      break
   fi

  done
fi

# Check if we need to unmount the proc in jail
mount | grep "${JDIR}/${IP}/proc" >/dev/null 2>/dev/null
if [ "$?" = "0" ]
then
  umount -f "${JDIR}/${IP}/proc"
fi

fi # End of FAST check

echo -e ".\c"

rm ${JDIR}/${IP}/var/run/warden.jid 2>/dev/null

echo -e "Done"


