#!/bin/bash

exec 3</dev/tty || exec 3<&0

echo
echo "+---- Stopping services .."
systemctl stop moosefs-chunkserver
if [ -f "/etc/default/moosefs-master" ]
then
  grep "MFSMASTER_ENABLE=true" "/etc/default/moosefs-master" >/dev/null 2>&1
  if [ ${?} -eq 0 ]
  then
    systemctl stop moosefs-master
  fi
fi
if [ -f "/etc/default/moosefs-metalogger" ]
then
  grep "MFSMETALOGGER_ENABLE=true" "/etc/default/moosefs-metalogger" >/dev/null 2>&1
  if [ ${?} -eq 0 ]
  then
    systemctl stop moosefs-metalogger
  fi
fi

grep -v ^# /etc/crypttab | while read line
do
  id=`echo $line | cut -f1 -d' '`
  if [ ${#id} -eq 36 ]
  then
    echo
    echo "+---- Unmounting file system for '${id}' .."
    mount | grep "^/dev/mapper/${id}" >/dev/null 
    if [ ${?} -eq 0 ]
    then
      umount "/chunks/${id}"
      if [ ${?} -ne 0 ]
      then
        echo "Error: umount did not execute successfully (${?}), exiting."
        exec 3<&- 
        exit 2
      fi
    else
      echo "Warning: file system already unmounted, skipping."
    fi
    echo "+---- Unmounting encrypted device '${id}' .."
    if [ -b "/dev/mapper/${id}" ]
    then
      cryptdisks_stop "${args[@]}" <&3 "${id}"
      if [ ${?} -ne 0 -o -b "/dev/mapper/${id}" ]
      then
        echo "Error: cryptdisks_stop did not execute successfully (${?}), exiting."
        exec 3<&- 
        exit 2
      fi
    else
      echo "Warning: encrypted device already unmounted, skipping."
    fi
  fi
done 

grep -v ^# /etc/fstab | grep -w chunks | while read line
do
  id=`echo $line | cut -f1 -d' '`
  if [ ${#id} -eq 41 ]
  then
    echo "+---- Unmounting file system for '${id}' .."
    mount | grep "^/dev/mapper/${id}" >/dev/null 
    if [ ${?} -eq 0 ]
    then
      umount "/chunks/${id}"
      if [ ${?} -ne 0 ]
      then
        echo "Error: umount did not execute successfully (${?}), exiting."
        exec 3<&- 
        exit 2
      fi
    else
      echo "Warning: file system already unmounted, skipping."
    fi
  fi
done 

echo
echo "+---- Done."

exec 3<&- 

