#!/bin/bash

main(){
  if [[ ${1} != "" && $(grep "^/dev/${1}\>" /proc/mounts) == "" ]] ; then
    local device_label=$(scan_device LABEL /dev/$1)
    local device_uuid=$(scan_device UUID /dev/$1)
    local device_type=$(scan_device TYPE /dev/$1)

    if [[ -f /etc/noautomount ]] ; then
      if [[ $(grep "^[[:space:]]*/dev/${1}\>" /etc/noautomount) == "" &&
            $(grep "^[[:space:]]*LABEL=${device_label}[[:space:]]*$" /etc/noautomount) == "" &&
            $(grep "^[[:space:]]*UUID=${device_uuid}[[:space:]]*$" /etc/noautomount) == ""  &&
            $(grep "^[[:space:]]*TYPE=${device_type}[[:space:]]*$" /etc/noautomount) == "" ]] ; then
        mount_attempt ${1}
      fi
    else
      mount_attempt ${1}
    fi
  fi
}

scan_device(){
  if [[ $2 != "" ]] ; then
    blkid $2 -s $1 | grep " $1=\"[[:print:][:space:]]*\" " | sed -e "s|^[[:print:]]*: $1=\"||" -e 's|" $||'
  else
    blkid -s $1 | grep " $1=\"[[:print:][:space:]]*\" " | sed -e "s|^[[:print:]]*: $1=\"||" -e 's|" $||'
  fi
}

mount_attempt(){
  if [[ $(echo "mount /mnt/${1}" | grep "^mount /mnt/[[:space:]]*$") == "" ]] ; then
    if [[ $device_type == "vfat" ]] ; then
      mount -o gid=p_removable,umask=007,users /dev/${1} /mnt/${1}
    else
      mount /dev/${1} /mnt/${1}
    fi
  fi
}

main ${1}
