#!/usr/bin/env bash

set -o errexit

print_help() {
    cat <<- EOF
Safely remove an external drive. Unmount and power-off device via udisksctl.

Usage: safeeject [-hv] [<mountpoint>]

Options:
    -h      print this help message and exit.
    -v      print version and exit.
EOF
}

yesno() {
    local answer=
    [ "$ASSUME_YES" ] && return 0

    while [ ! "$answer" ]; do
        echo -en "$@ (answer 'yes' to proceed) "
        read -r reply
        case "${reply,,}" in
            yes) answer=0;;
            *)  answer=1;;
        esac
    done
    return "$answer"
}

resolve_device() {
    case "$1" in
        /dev/sd*|/dev/hd*)
            local del="$(echo "$1" | grep -Po '(?<=[a-z])([0-9]+)$')";;
        /dev/nvme*)
            local del="$(echo "$1" | grep -Po '(?<=[0-9])?([a-z])([0-9]+)$')";;
        *)
            echo -e "\e[91mCannot parse device name\e[0m"; return;;
    esac
    echo "${1//$del}"
}

while getopts hv OPT; do
    case $OPT in
        h) print_help; exit 0;;
        v) echo 1.1; exit 0;;
    esac
done
shift $((OPTIND-1))
point="$1"

if [[ "$UID" != 0 ]]; then
    echo -e "\e[91mYou arn't root!\e[0m" >&2; exit 1
fi

if ! hash udisksctl &>/dev/null; then
    echo -e '\e[91mudisksctl utility not found!\e[0m' >&2; exit 1
fi

[ "$point" ] || { echo -e '\e[91mNo mountpoint specified\e[0m'; exit 1; }

if [[ "$point" == '/' ]]; then
    echo -e '\e[91mCannot unmount root\e[0m'; exit 1
fi

echo -e "Mountpoint: \e[1m${point%%/}\e[0m"

partition="$(mount | grep " ${point%%/} " | tee /dev/stderr | awk '{print $1}')"
if [ "$partition" ]; then
    echo -e "Partition: \e[1m${partition}\e[0m"
else
    echo -e "\e[91mNo filesystems mounted on ${point%%/}\e[0m"; exit 1
fi

device="$(resolve_device "$partition")"
echo -e "Device: \e[1m${device}\e[0m"
if [[ ! "$device" =~ Cannot.* ]]; then
    fdisk --color=never --list "$device"
else
    exit 1
fi

# Do not allow poweroff the system disk!
root_partition="$(mount | grep " / " | tee /dev/stderr | awk '{print $1}')"
root_device="$(resolve_device "$root_partition")"
if [[ "$device" == "$root_device" ]]; then
    echo -e '\e[91mYou cannot eject primary disk!\e[0m'; exit 1
fi

echo -e "\n\e[91mDo not continue if device is not detected correctly," \
    "instead unmount and poweroff the device manually!\e[0m"

if yesno "Is $device the correct device?"; then
    echo Sync to disk ...
    sync
    sleep 5
    echo Unmounting $partition ...
    if udisksctl unmount -b "$partition"; then
        sleep 1
    else
        exit 1
    fi
    echo Power off device $device ...
    if udisksctl power-off -b "$device"; then
        sleep 2
        echo -e '\e[92mNow you can safely eject device\e[0m'
    else
        exit 1
    fi
else
    echo Abort; exit 1
fi
