#!/bin/bash

if [ "$1" == "" ]; then
  echo "Usage: $0 <dev name> [-u]"
  exit 1
fi

DEV=/dev/$1

if [ "$2" == "-u" ]; then
  if [ -e $DEV ]; then
    MOUNT_POINT=$(
      sed -n "s/^\/dev\/$1 \([^ ]*\) .*/\1/p;s/\\040/ /g" /proc/mounts)
    systemd-umount $DEV
    rmdir "$MOUNT_POINT"
  fi
else
  eval $(/sbin/blkid -o udev -p $DEV)

  if [ "$ID_FS_USAGE" != "filesystem" ]; then
    echo "$DEV not a filesystem"
    exit 0
  fi

  MOUNT_POINT=$ID_FS_LABEL
  if [ "$MOUNT_POINT" == "" ]; then
    MOUNT_POINT=USB_DISK-$1
  fi
  MOUNT_POINT=/media/"$MOUNT_POINT"

  OPTS=relatime,noauto #,users

  if [ "$ID_FS_TYPE" == "vfat" -o "$ID_FS_TYPE" == "ntfs" ]; then
    OPTS+=",utf8,gid=1000,umask=002,sync"
  fi

  mkdir -p "$MOUNT_POINT"

  MOUNT_POINT=$(echo -n "$MOUNT_POINT" | sed 's/ /\\040/g')

  systemd-mount --no-block --collect -o $OPTS $DEV "$MOUNT_POINT"
fi
