summaryrefslogtreecommitdiff
path: root/src/usb
blob: a8ab01572ad2b1dd7bbab195dc4df6dbf44067e2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#!/bin/bash

die() { printf "%s: Error: %s\n" "$0" "$*" >&2; exit 1; }

ECHO() { printf "%s\n" "$*" >&2; }

PRINTF() { printf "$@" >&2; }

whole_device()
{
    case "$1" in
        *-part?) false ;;
        *-part??) false ;;
        *-part???) false ;;
        */usb\*) false ;;
        *) true ;;
    esac
}

confirm_usb_strict()
{
    CONFIRM_MSG="This will completely overwrite device:\n\n\t%s\n\nType 'yes' to confirm.\nContinue? "
    CONFIRM_WITH_ONE_LETTER=
    confirm_helper "$@"
}

confirm_usb_lax()
{
    CONFIRM_MSG="The device used will be:\n\n\t%s\n\nType 'y' to confirm.\nContinue? "
    CONFIRM_WITH_ONE_LETTER=y
    confirm_helper "$@"
}

confirm_helper()
{
    PRINTF "$CONFIRM_MSG" "$1"
    read line
    case "$line" in
        [yY][eE][sS]) return ;;
        [yY]) [ "$CONFIRM_WITH_ONE_LETTER" ] && return || : ;;
    esac
    die "Aborted by user."
}

choose_usb()
{
    local devs maj USB
    set -- /dev/disk/by-id/usb*
    for dev; do
        shift
        whole_device "$dev" || continue
        set -- "$@" "$dev"
    done
    if [ $# = 0 ]; then
        die "no USB storage device found"
    elif [ $# = 1 ]; then
        [ "$NO_ACT" ] && confirm=confirm_usb_lax || confirm=confirm_usb_strict
        $confirm "$1" || exit
        USB=$1
    else
        ECHO
        PRINTF "%s\n" "The following candidate target devices have been found:"
        i=0
        for dev; do
            i=$((i+1))
            PRINTF "\n\n\t%2i. %s\n" $i "$dev"
        done
        PRINTF "%s\n\n" '' "Choose a device by its number, from 1 to $#, then press enter." "To abort, press CTRL-C."
        PRINTF "\n%s" 'Your choice: '
        read line
        case "$line" in
            [1-9]|[1-9][0-9])
                [ $line -le $# -a $line -ge 1 ] || die "Invalid argument (out of range): $line"
                USB=${!line}
                ;;
            *) die "Invalid argument: $line" ;;
        esac
        confirm_usb_lax
    fi
    [ "$USB" ] && readlink -f "$USB"
}

NO_ACT=
case "$1" in
    -n) NO_ACT=y;;
    -*) exit 1;;
esac

choose_usb