#! /bin/bash

echo "Starting MistServer removal script."

if [ "`whoami`" != "root" ]; then
  echo "Must be root to remove"
  exec su -c $0 
fi

read -r -p "Are you sure you want to remove MistServer? [y/N] " response </dev/tty
case $response in
  [yY][eE][sS]|[yY]) 
    echo "Removing MistServer while keeping configurations..."
    echo "Attempting to shut down any running MistController."
    kill `pidof MistController` 2> /dev/null
    timer=0
    while [ "`pidof MistController`" != "" ] ; do
      if [[ $timer == 10 ]] ; then
        echo "MistController shutting down too slow, assuming crash and forcing shutdown."
        LOC=`pwd`
        cd `dirname \`which MistController\` 2> /dev/null`
        kill -9 `pidof Mist*` 2> /dev/null
        cd $LOC
      else
        sleep 1
        timer=$(($timer+1))
        echo "$timer"
      fi
    done
    
    echo "Removing service files"
    systemctl stop mistserver 2> /dev/null
    systemctl disable mistserver 2> /dev/null
    service mistserver stop 2> /dev/null
    chkconfig mistserver off 2> /dev/null
    rm /etc/systemd/system/mistserver.service 2> /dev/null
    rm /etc/init.d/mistserver 2> /dev/null
      
    rm /dev/shm/*Mst* 2> /dev/null
    echo "Removing MistController."
    INST_DIR=`dirname \`which MistController 2> /dev/null \` 2> /dev/null` 
    if [ "$INST_DIR" != "" ] ; then
      rm -rf $INST_DIR/Mist* 2> /dev/null
    fi
    
    read -r -p "Would you like to remove MistServer configurations as well? [y/N] " response2 </dev/tty
    case $response2 in
      [yY][eE][sS]|[yY]) 
        echo "Removing MistServer and configurations..."
        rm -f /etc/mistserver.conf
        ;;
      *)
        echo "Keeping MistServer configurations..."
        ;;
    esac
    echo "Finished removing MistServer."
    ;;  
  *)
    echo "Aborting."
    ;;
esac





