#!/bin/bash
# Mount/unmount Android phones over MTP via gvfs, exposed as ~/Phone
# Usage: phone [mount|umount]

link="$HOME/Phone"

case "${1:-mount}" in
mount)
    gio mount -li | sed -n 's/^ *activation_root=\(mtp:.*\)/\1/p' |
        while read -r uri; do gio mount "$uri"; done

    mounts=("$XDG_RUNTIME_DIR"/gvfs/mtp:host=*)
    if [[ ! -e ${mounts[0]} ]]; then
        echo "phone: no MTP device mounted" >&2
        exit 1
    fi
    if [[ -e $link && ! -L $link ]]; then
        echo "phone: $link exists and is not a symlink" >&2
        exit 1
    fi
    ln -sfn "${mounts[0]}" "$link"
    ;;
umount)
    gio mount -s mtp
    if [[ -L $link ]]; then rm "$link"; fi
    ;;
*)
    echo "usage: ${0##*/} [mount|umount]" >&2
    exit 1
    ;;
esac
