#!/bin/bash

# Enable Execution on FAT and NTFS.bash
# 2013-03-04
# Chieh Cheng
# http://www.CynosureX.com/

# GNU General Public License (GPL) Version 2, June 1991

  scriptName=`basename "$0"`

function checkDaemon ()
{
  daemonPath="$1"
  result=`grep -bc "showexec" "${daemonPath}"`

  echo ${result}
}

function findUdiskDaemon ()
{
  daemon="/usr/lib/udisks2/udisksd"

  if [ ! -f "${daemon}" ]
  then
    daemon="/usr/lib/udisks/udisks-daemon"
  fi

  if [ ! -f "${daemon}" ]
  then
    daemon=""
  fi

  echo "${daemon}"
}

function patchDaemon ()
{
  daemonPath="$1"
  daemonDir=`dirname "${daemonPath}"`
  daemonName=`basename "${daemonPath}"`
  backup="${daemonDir}/${daemonName}.backup"

  echo "udisk daemon found in \"${daemonPath}\""
  echo "A backup copy will be created here: \"${backup}\""
  echo "If a backup already exists, then another backup will NOT be made."
  echo "sudo password is needed to continue."

  if [ ! -f "${backup}" ]
  then
    sudo cp -p "${daemonPath}" "${backup}"
    echo "Created \"${backup}\"."
  else
    echo "${backup} already exist. No backup made."
  fi

  sudo sed -i -e 's|showexec|\x00\x00\x00\x00\x00\x00\x00\x00|g' "${daemonPath}"
  echo "Patch to \"${daemonPath}\" successful."
  echo "You must now restart your computer in order for the change to take effect."
}

function process ()
{
  daemonPath=`findUdiskDaemon`

  if [ "${daemonPath}" = "" ]
  then
    echo "udisk daemon not found!"
  else
    okToPatch=`checkDaemon "${daemonPath}"`

    if [ ${okToPatch} -eq 1 ]
    then
      patchDaemon "${daemonPath}"
    else
      echo "udisk daemon doesn't not contain signature needed to patch."
      echo "udisk daemon: \"${daemonPath}\""
    fi
  fi
}

function usage ()
{
  echo "  Usage:   \"${scriptName}\""
}

  if [ $# -eq 0 ]
  then
    process
  else
    usage
  fi
