#!/bin/bash

# Source function library.
if [ -r /etc/init.d/functions ]; then
    . /etc/init.d/functions
fi

# Define LSB log_* functions.
# Depend on lsb-base (>= 3.0-6) to ensure that this file is present.
if [ -r /lib/lsb/init-functions ]; then
    . /lib/lsb/init-functions
fi

BASEMAPR=${MAPR_HOME:-/opt/mapr}
PATH=$PATH:/sbin:/usr/sbin:/bin:/usr/bin:/usr/local/bin
PATH=$BASEMAPR/bin:$PATH

env=${BASEMAPR}/conf/env.sh
[ -f $env ] && . $env

# Exit if JAVA_HOME is not set
if [ -z "$JAVA_HOME" ]; then
  echo "JAVA not found. Exiting..."
  exit 1
fi

# remove trailing slash from JAVA_HOME
case $JAVA_HOME in
  *[!/]*/) JAVA_HOME=${JAVA_HOME%"${JAVA_HOME##*[!/]}"};;
esac

# Find libjvm.so
if [[ $JAVA_HOME == *"jre" ]]
then
  LIBJVM_PATH=${JAVA_HOME}/lib/amd64/server
else
  LIBJVM_PATH=${JAVA_HOME}/jre/lib/amd64/server
fi

if [ ! -f "$LIBJVM_PATH/libjvm.so" ]; then
  echo "libjvm.so not found. Exiting..."
  exit 1
fi

# Check whether the fuse.conf file exists.
FUSE_CONFFILE_PATH="$BASEMAPR/conf"
FUSE_CONFFILE_NAME="fuse.conf"
FUSE_CONFFILE="$FUSE_CONFFILE_PATH/$FUSE_CONFFILE_NAME"
if [ ! -f $FUSE_CONFFILE ]; then
  echo "$FUSE_CONFFILE_NAME file not found in $FUSE_CONFFILE_PATH. Exiting..."
  exit 1
fi

if [ ! -r $FUSE_CONFFILE ]; then
  echo "Unable to read $FUSE_CONFFILE_NAME. Exiting..."
  exit 1
fi

# Check if fuse log file can written and change its permissions.
FUSE_LOG_PATH=`awk -F =  '$1 == "fuse.log.path" { print $2 }' $FUSE_CONFFILE | xargs`
if [ "$FUSE_LOG_PATH" = "" ]; then
  FUSE_LOG="$BASEMAPR/logs/${POSIX_CLIENT_NAME}.log"
else
  FUSE_LOG="$FUSE_LOG_PATH/${POSIX_CLIENT_NAME}.log"
fi

touch $FUSE_LOG > /dev/null 2>&1
if [ $? -ne 0 ]; then
  echo "Unable to create log file $FUSE_LOG, probably incorrect path in conf file"
  return 1
fi

if [ ! -w "$FUSE_LOG" ]; then
  echo "Unable to write to $FUSE_LOG. Exiting..."
  exit 1
fi
chmod 600 $FUSE_LOG;

# Check whether the mapr-fuse client exists.
POSIX_CLIENT_PATH="$BASEMAPR/bin"
POSIX_CLIENT="$POSIX_CLIENT_PATH/$POSIX_CLIENT_NAME"
if [ ! -f "$POSIX_CLIENT" ]; then
  ts=`date`
  echo "$POSIX_CLIENT_NAME not found in $POSIX_CLIENT_PATH. Exiting..."
  echo "$ts: $POSIX_CLIENT_NAME not found in $POSIX_CLIENT_PATH. Exiting..." >> $FUSE_LOG
  exit 1
fi

INITSCRIPT_NAME="/etc/init.d/mapr-$POSIX_CLIENT_NAME"
SYSTEMD_NAME="/etc/systemd/system/mapr-${POSIX_CLIENT_NAME}.service"

# Get the mount point from configuration file. If mount point not specified,
# then posix client binary will exit
MOUNT_POINT=$( awk -F = '$1 == "fuse.mount.point" { print $2 }' $FUSE_CONFFILE )

# Get the client library path from configuration file. If not specified ,
# then will use \tmp for client libraries.
FUSE_CLIENT_LIB_PATH=`awk -F =  '$1 == "fuse.client.lib.path" { print $2 }' $FUSE_CONFFILE | xargs`
if [ "$FUSE_CLIENT_LIB_PATH" = "" ]; then
  FUSE_CLIENT_LIB_PATH="/tmp"
fi

if [ ! -d "$FUSE_CLIENT_LIB_PATH" ]; then
  echo "fuse client lib path <$FUSE_CLIENT_LIB_PATH> does not exists"
  exit 1
fi
FUSE_CLIENT_LIB="libMapRClient.so"

# Check whether the same script is already running or not.
# if its already running then exit.
lock_for_single_instance() {
  # Check whether the lock file can be created.
  TMP_DIR="/tmp"
  if [ ! -w $TMP_DIR ]; then
    echo "$TMP_DIR is not writable. Exiting..."
    ts=`date`
    echo "$ts: $TMP_DIR is not writable. Exiting..." >> $FUSE_LOG
    exit 1
  fi

  PROC_NAME=`basename "$0"`;
  LOCK="$TMP_DIR/$PROC_NAME.lck"
  exec 7>$LOCK;

  if ! flock -n -x 7; then
    OTHER_USER=`stat -c %U $LOCK`
    if [ "$OTHER_USER" = $USER ]; then
      echo "Failed to operate on \"$PROC_NAME\" because $LOCK exists and/or operation may be in progress."
    else
      echo "Failed to modify \"$PROC_NAME\" as user \"$USER\", as $LOCK exists and/or is owned by \"$OTHER_USER\". Exiting..."
    fi
    ts=`date`
    echo "$ts Pid $$: Failed to modify $PROC_NAME as user \"$USER\", as $LOCK exists and/or is owned by \"$OTHER_USER\"." >> $FUSE_LOG
    lsof $LOCK >> $FUSE_LOG 2>&1
    exit 1
  fi
}

unLock_for_single_instance() {
  flock -u 7
  rm -f $LOCK
}

kill_client_processes()
{
  #
  # REMINDER: If the parameters for killproc should
  # change in this function, then the parameters need
  # to be verified against SuSE in order to maintian
  # support.
  #
  local delay="-d 10"

  if [ -f "/etc/SuSE-release" ]; then
      delay="-t 10"
  fi

  killproc ${delay} $POSIX_CLIENT
  killproc ${delay} "fusermount"
  return 0;
}


# Function to mount the filesystem, if not already mounted.
do_start()
{
  # Set for libjvm.so and libMapRClient.so
  export LD_LIBRARY_PATH="$LIBJVM_PATH:$BASEMAPR/lib:$LD_LIBRARY_PATH"

  # Increasing open fd limit
  ulimit -n 65536

  # Check if filesystem is already mounted
  get_status
  if [ $? == 1 ]; then
    echo "$POSIX_CLIENT_NAME is already mounted."
    ts=`date`
    echo "$ts: $POSIX_CLIENT_NAME is already mounted." >> ${FUSE_LOG}
    return 1
  fi

  # check if mountpoint is non empty and nonempty option is false
  NONEMPTY=`awk -F =  '$1 == "fuse.nonempty" { print $2 }' $FUSE_CONFFILE`
  if [ "$NONEMPTY" = "" ] || [ $NONEMPTY -eq 0 ]; then
    if [ "$(ls -A $MOUNT_POINT)" ]; then
      echo "$MOUNT_POINT is not empty and nonempty option is not used"
      return 1
    fi
  fi
  # Killing old posix client processes here if user had done umount -f
  kill_client_processes
  # setup hostname as it may not exist on client machines
  HOSTNAME_FILE="$BASEMAPR/hostname"
  if [ ! -r $HOSTNAME_FILE ]; then
    ts=`date`
    echo "$ts: Creating ${HOSTNAME_FILE}" >> ${FUSE_LOG}
    echo `/bin/hostname --fqdn` > ${HOSTNAME_FILE}
  fi

  if [ $? -ne 0 ]; then
    echo "INFO: cmd /bin/hostname --fqdn failed"
    ts=`date`
    echo "$ts: INFO: cmd /bin/hostname --fqdn failed" >> ${FUSE_LOG}
    return 1
   fi

# Same way, check and create hostid file if does not exist

  CLIENT_LIB_PATH=$BASEMAPR/lib/fuselib/$FUSE_CLIENT_LIB;
  if [ ! -r $CLIENT_LIB_PATH ]; then
    CLIENT_LIB_PATH=$BASEMAPR/lib/$FUSE_CLIENT_LIB;
  fi

  if [ ! -r $CLIENT_LIB_PATH ]; then
    echo "Unable to read $CLIENT_LIB_PATH"
    ts=`date`
    echo "Unable to read $CLIENT_LIB_PATH" >> ${FUSE_LOG}
    return 1
  fi
  # create FUSE_CLIENT_LIB copies
  NUM_LIBS=`awk -F =  '$1 == "fuse.num.libs" { print $2 }' $FUSE_CONFFILE`
  if [ "$NUM_LIBS" = "" ]; then
    NUM_LIBS="$DEFAULT_NUM_LIBS"
  fi
  if [ $NUM_LIBS -gt $ALLOWED_NUM_LIBS ]; then
    echo "Current license does not allow" $NUM_LIBS "libs, starting with" ALLOWED_NUM_LIBS "libs"
    NUM_LIBS=${ALLOWED_NUM_LIBS}
  fi
  i=0
  while [ $i -lt $NUM_LIBS ]
  do
#    msg="copying $BASEMAPR/lib/$FUSE_CLIENT_LIB to $FURSE_CLIENT_LIB_PATH/$FUSE_CLIENT_LIB.$i"
#    echo $msg
#    ts=`date`
#    echo "$ts: $msg" >> $FUSE_LOG
    cp $CLIENT_LIB_PATH $FUSE_CLIENT_LIB_PATH/$FUSE_CLIENT_LIB.$i
    i=`expr $i + 1`
  done

  # if ticket file location specified, export path to "MAPR_TICKETFILE_LOCATION"
  TicketFile=`awk -F =  '$1 == "fuse.ticketfile.location" { print $2 }' $FUSE_CONFFILE | xargs`
  if [ "$TicketFile" != "" ]; then
    export MAPR_TICKETFILE_LOCATION=$TicketFile
  fi

  # check for the core pattern
  FUSE_CORE_PATTERN=`awk -F = '$1 == "fuse.enforce.core.pattern" { print $2 }' $FUSE_CONFFILE`
  if [ "$FUSE_CORE_PATTERN" == true ]; then
    echo "/opt/cores/%e.core.%p.%h" > /proc/sys/kernel/core_pattern
  fi

  # Start mapr-fuse daemon
  FUSE_ARGS=$( awk -v num_libs="$NUM_LIBS" -F = '
                 $1 == "fuse.mount.point" { print $2 }
                 $1 == "fuse.log.path" { print "--log_path " $2 }
                 $1 == "fuse.client.lib.path" { print "--client_lib_path " $2 }
                 $1 == "fuse.allow.other" { if ($2 == 1) print "-o allow_other" }
                 $1 == "fuse.num.libs" { print "--num_libs " num_libs }
                 $1 == "fuse.affinity" { if ($2 == 1) print "--use_affinity" }
                 $1 == "fuse.ra.sessions" { print "--ra_sessions=" $2 }
                 $1 == "fuse.num.threads" { print "--num_threads=" $2 }
                 $1 == "fuse.auto.unmount" { if ($2 == 1) print "-o auto_unmount" }
                 $1 == "fuse.auto.inval.data" { if ($2 == 1) print "-o auto_inval_data" }
                 $1 == "fuse.asyncdirect.io" { if ($2 == 1) print "-o async_dio" }
                 $1 == "fuse.max.read" { print "-o max_read=" $2 }
                 $1 == "fuse.max.readahead" { print "-o max_readahead=" $2 }
                 $1 == "fuse.max.write" { print "-o max_write=" $2 }
                 $1 == "fuse.sync.read" { if ($2 == 1) print "-o sync_read" }
                 $1 == "fuse.max.background" { print "-o max_background=" $2 }
                 $1 == "fuse.congestion.threshold" { print "-o congestion_threshold=" $2 }
                 $1 == "fuse.big.writes" { print "-o big_writes" }
                 $1 == "fuse.flush.inline" { if ($2 == 1) print "--flush_inline" }
                 $1 == "fuse.fast.local.directio" { if ($2 == 1) print "--fast_local_direct_io" }
                 $1 == "fuse.disable.shardcache" { if ($2 == 1) print "--disable_shardcache" }
                 $1 == "fuse.fsname" { print "-o fsname=" $2 }
                 $1 == "fuse.nonempty" { if ($2 == 1) print "-o nonempty" }
                 $1 == "fuse.xattr.enable" { if ($2 == 1) print "--enable_xattr" }
                 $1 == "fuse.attr.timeout" { print "--attr_timeout " $2 }
                 $1 == "fuse.entry.timeout" { print "--entry_timeout " $2 }
                 $1 == "fuse.hb.interval" { print "--hb_interval " $2 }
                 $1 == "fuse.export" { print "--fuse_export " $2 }
                 $1 == "fuse.access.type" { print "-o " $2 }
                 $1 == "fuse.disable.writeback" { if ($2 == 1) print "--disable_writeback" }
		 ' $FUSE_CONFFILE )
  FUSE_ARGS=${FUSE_ARGS//$'\n'/$' '}

  ulimit -c unlimited >> $FUSE_LOG 2>&1
  ulimit -l unlimited >> $FUSE_LOG 2>&1

  ts=`date`
  echo "$ts: Mounting $POSIX_CLIENT_NAME $FUSE_ARGS at $MOUNT_POINT ..." >> $FUSE_LOG

  if [ -f /etc/SuSE-release ]; then
    start_daemon $POSIX_CLIENT $FUSE_ARGS >> $FUSE_LOG 2>&1
    ret=$?
  else
    $POSIX_CLIENT $FUSE_ARGS >> $FUSE_LOG 2>&1
    ret=$?
  fi

  ret=$?
  echo "$ts: Result:$ret" >> $FUSE_LOG
  return $ret
}

# Function to unmount the filesystem, if not already unmounted.
do_stop()
{
  get_status
  if [ $? != 1 ]; then
    echo "$POSIX_CLIENT_NAME is not mounted."
    ts=`date`
    echo "$ts: $POSIX_CLIENT_NAME is not mounted." >> ${FUSE_LOG}
    return 0
  fi
  ret=0
  # Unmount and kill all processes.
  msg="umount $MOUNT_POINT 2>&1"
  ts=`date`
  echo "Running umount $MOUNT_POINT"
  echo "$ts: $msg" >> $FUSE_LOG
  umount  $MOUNT_POINT
  ret=$?

  if [ $ret != 0 ]; then
    echo "Umounting failed $ret, killing fuse thread anyway" >> ${FUSE_LOG}
  fi

  kill_client_processes
  if [ $? != 0 ]; then
    echo "Could not kill the client processes" >> ${FUSE_LOG}
    return 1
  fi

  rm -rf $FUSE_CLIENT_LIB_PATH/$FUSE_CLIENT_LIB.*
  echo "$POSIX_CLIENT_NAME stopped successfully."
  return 0
}

do_exit()
{
  # Remove the lock. 
  unLock_for_single_instance
  exit $1
}

get_status()
{
  if cat "/proc/mounts" | grep -F "$POSIX_CLIENT_NAME" > "/dev/null"; then
    return 1
  else
    return 0
  fi
}

if [ "$1" = "-h" ]; then
  if [ -x "${INITSCRIPT_NAME}" ]; then
    msg="Usage: $INITSCRIPT_NAME {start|stop|status|restart}"
  elif [ -f "${SYSTEMD_NAME}" ]; then
    msg="Usage: systemctl {start|stop|status|restart} mapr-${POSIX_CLIENT_NAME}"
  else
    msg="WARN - did not detect either ${INITSCRIPT_NAME} or ${SYSTEMD_NAME}"
  fi
  echo $msg
  ts=`date`
  echo "$ts: $msg" >> $FUSE_LOG
  exit 0
fi

# Put the lock.
lock_for_single_instance
  option="$1"
  ts=`date`
  echo "$ts: Running $0 $option" >> $FUSE_LOG
case "$1" in
  start)
    do_start
    ;;
  stop)
    do_stop
    ;;
  status)
    get_status
    if [ $? == 1 ]; then
      msg="$POSIX_CLIENT_NAME is mounted at $MOUNT_POINT."
    else
      msg="$POSIX_CLIENT_NAME is not mounted."
    fi
    echo $msg
    ts=`date`
    echo "$ts: $msg" >> $FUSE_LOG
    ;;
  restart)
    do_stop
    if [ $? -eq 0 ]
    then
      do_start
    fi
    ;;
  *)
    if [ -x "${INITSCRIPT_NAME}" ]; then
      msg="Usage: $INITSCRIPT_NAME {start|stop|status|restart}"
    elif [ -f "${SYSTEMD_NAME}" ]; then
      msg="Usage: systemctl {start|stop|status|restart} mapr-${POSIX_CLIENT_NAME}"
    else
      msg="WARN - did not detect either ${INITSCRIPT_NAME} or ${SYSTEMD_NAME}"
    fi
    echo $msg
    ts=`date`
    echo "$ts: $msg" >> $FUSE_LOG
    do_exit 2
    ;;
esac

ret=$?
do_exit $ret
