developer | 68989f1 | 2022-12-19 15:14:00 +0800 | [diff] [blame] | 1 | #!/bin/bash |
| 2 | |
| 3 | # This script is called from our systemd unit file to mount or unmount |
| 4 | # a USB drive. |
| 5 | |
| 6 | usage() |
| 7 | { |
| 8 | echo "Usage: $0 {add|remove} device_name (e.g. sdb1)" |
| 9 | exit 1 |
| 10 | } |
| 11 | |
| 12 | if [[ $# -ne 2 ]]; then |
| 13 | usage |
| 14 | fi |
| 15 | |
| 16 | ACTION=$1 |
| 17 | DEVBASE=$2 |
| 18 | DEVICE="/dev/${DEVBASE}" |
| 19 | |
| 20 | # See if this drive is already mounted, and if so where |
| 21 | MOUNT_POINT=$(mount | grep ${DEVICE} | awk '{ print $3 }') |
| 22 | |
| 23 | DEV_LABEL="" |
| 24 | |
| 25 | do_mount() |
| 26 | { |
| 27 | if [[ -n ${MOUNT_POINT} ]]; then |
| 28 | echo "Warning: ${DEVICE} is already mounted at ${MOUNT_POINT}" |
| 29 | exit 1 |
| 30 | fi |
| 31 | |
| 32 | # Get info for this drive: $ID_FS_LABEL and $ID_FS_TYPE |
| 33 | eval $(blkid -o udev ${DEVICE} | grep -i -e "ID_FS_LABEL" -e "ID_FS_TYPE") |
| 34 | |
| 35 | # Figure out a mount point to use |
| 36 | LABEL=${ID_FS_LABEL} |
| 37 | if grep -q " /media/${LABEL} " /etc/mtab; then |
| 38 | # Already in use, make a unique one |
| 39 | LABEL+="-${DEVBASE}" |
| 40 | fi |
| 41 | DEV_LABEL="${LABEL}" |
| 42 | |
| 43 | # Use the device name in case the drive doesn't have label |
| 44 | if [ -z ${DEV_LABEL} ]; then |
| 45 | DEV_LABEL="${DEVBASE}" |
| 46 | fi |
| 47 | |
| 48 | MOUNT_POINT="/media/${DEV_LABEL}" |
| 49 | |
| 50 | echo "Mount point: ${MOUNT_POINT}" |
| 51 | |
| 52 | mkdir -p ${MOUNT_POINT} |
| 53 | |
| 54 | # Global mount options |
| 55 | OPTS="rw,relatime" |
| 56 | |
| 57 | # File system type specific mount options |
| 58 | if [[ ${ID_FS_TYPE} == "vfat" ]]; then |
| 59 | OPTS+=",users,gid=100,umask=000,shortname=mixed,utf8=1,flush" |
| 60 | fi |
| 61 | |
| 62 | if ! mount -o ${OPTS} ${DEVICE} ${MOUNT_POINT}; then |
| 63 | echo "Error mounting ${DEVICE} (status = $?)" |
| 64 | rmdir "${MOUNT_POINT}" |
| 65 | exit 1 |
| 66 | fi |
| 67 | |
| 68 | echo "Mounted ${DEVICE} at ${MOUNT_POINT}" |
| 69 | } |
| 70 | |
| 71 | do_unmount() |
| 72 | { |
| 73 | if [[ -z ${MOUNT_POINT} ]]; then |
| 74 | echo "Warning: ${DEVICE} is not mounted" |
| 75 | else |
| 76 | umount -l ${DEVICE} |
| 77 | echo "Unmounted ${DEVICE} from ${MOUNT_POINT}" |
| 78 | /bin/rmdir "${MOUNT_POINT}" |
| 79 | fi |
| 80 | |
| 81 | |
| 82 | } |
| 83 | |
| 84 | case "${ACTION}" in |
| 85 | add) |
| 86 | do_mount |
| 87 | ;; |
| 88 | remove) |
| 89 | do_unmount |
| 90 | ;; |
| 91 | *) |
| 92 | usage |
| 93 | ;; |
| 94 | esac |