#!/bin/bash
set -e

# TODO
# mount all partitions by selecting disk
# usage
# support for /mnt

function get_row() {
    local pos row

    printf '\e[6n' >&2
    read -sdRr pos
    pos="${pos#*[}"
    row="${pos%;*}"
    echo "$row"
}

ROW="$(($(get_row) + 1))"
function clear_output() {
    local row

    row="$(get_row)"
    for _ in $(seq "$ROW" "$row"); do
        printf '\e[1A\e[K'
    done
}

function umount_all() {
    local disks

    readarray -t disks <<< "$(mount | grep udisks2 | cut -f1 -d' ')"

    umount "${disks[@]}"
    echo "unmounted ${disks[*]}"
}

if ! [ -t 1 ]; then
    exit 1
fi

while getopts a o; do
    case "$o" in
        a)
            umount_all
            exit
            ;;
        *)
            ;;
    esac
done

while true; do
    #readarray -t LSBLK <<< "$(lsblk -n --paths | grep -v snap)"
    readarray -t LSBLK <<< "$(lsblk -n --paths --list | grep part)"

    COLUMNS=1
    select dev in "${LSBLK[@]}"; do
        name="$(cut -f1 -d' ' <<< "$dev")"

        clear_output
        if mount | grep -q "$name"; then
            umount "$name"
        else
            udisksctl mount -b "$name" > /dev/null
        fi
        break
    done || exit
done
