#!/bin/bash

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

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

echo
echo "+---- Restarting services .."
if [ -f "/etc/default/moosefs-master" ]
then
  grep "MFSMASTER_ENABLE=true" "/etc/default/moosefs-master" >/dev/null 2>&1
  if [ ${?} -eq 0 ]
  then
    systemctl restart 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 restart moosefs-metalogger
  fi
fi
systemctl restart moosefs-chunkserver

echo
echo "+---- Done."

exec 3<&- 

