#!/usr/bin/bash
[ ${BASH_VERSION%%.*} -ge 4 ] || exit 1

LANG=en_US.UTF-8
export LANG
SCRIPT=$(readlink -f $0)
WHERE=${SCRIPT%/*}

usage() {
  echo ""
  echo "usage: ${0##*/} [ --help | -a | -l | <mount dir> ]"
  echo ""
}

usagelong() {
usage
cat << EOF
                : without any parameter it does -l
    -a|--all    : umount all fuse.sshfs mounts
    -l|--list   : list all fuse.sshfs mounts

    <mount dir> : what dir to fuse.sshfs umount

    -h          : short help
    --help      : this longer help

EOF
}

[[ $1 =~ ^-h ]] && usage && exit 0
[[ $1 =~  ^--help ]] && usagelong && exit 0

MOUNTDIR=$(readlink -f ${HOME}/sshfs)

if [[ $1 =~ -l|--list ]] || [ $# -lt 1 ]; then
  mount | grep ${MOUNTDIR} | awk '/ type fuse.sshfs /''{ print $1 " " $2 " " $3 }' | sed "s|${MOUNTDIR}/|~/sshfs/|g"
  exit 0
fi

if [[ $1 =~ -a|--all ]]; then
  FSUMOUNT=$(mount | grep ${MOUNTDIR} | awk '/ type fuse.sshfs /''{ print $3 }')
  [ -z "${FSUMOUNT}" ] && exit 0
else
  FSUMOUNT=$(mount | grep " on ${MOUNTDIR}/$1 type fuse.sshfs " | awk '{ print $3 }' | head -n1)
fi

if [ -z "${FSUMOUNT}" ]; then
  echo "ERROR nothing found to umount with $1"
  exit 1
fi

for i in ${FSUMOUNT} ; do
  fusermount -u ${i}
  if [ $? -eq 0 ]; then
    rmdir ${i}
  fi
done

# cleanup what is not used
rmdir ${MOUNTDIR}/* 2>/dev/null
