#!/bin/sh
export PATH=$PATH:'/usr/gnu/bin:/usr/local/bin:/bin:/usr/bin:/sbin/:/usr/sbin/.'
if [ -x "$(command -v readlink)" ]
then
    case $1 in
    list)
        usb_links=$(ls -1 /dev/disk/by-path/*usb* 2>/dev/null)
        test -z "$usb_links" && exit 1
        devs=$(echo "$usb_links"|xargs -I% readlink '%'|sed 's%\.\./\.\./%/dev/%'|fgrep -f - /proc/mounts|sed 's%^/dev/\([^[:blank:]]*\)[[:blank:]]*.*$%\1%')
        test -z "$devs" && exit 1
        for f in /dev/disk/by-uuid/*
        do
            link=`readlink "$f"`
            ( echo "${link}_vfat" "${link}_fat" "${link}_ext4" "${link}_ntfs" "${link}" | fgrep -qw "$devs" ) && echo $f
        done|sed 's%/dev/disk/by-uuid/%%'
        exit 0
        ;;
    find)
        fname="/dev/disk/by-uuid/$2"
        test -L "$fname" || exit 1
        link=$(readlink "$fname" | sed 's%\.\./\.\./%/dev/%')
        link=$( fgrep -ow -e "${link}_vfat" -e "${link}_fat" -e "${link}_ext4" -e "${link}_ntfs" -e "${link}" /proc/mounts 2>/dev/null )
        printf "$(echo "$link"| fgrep -wf - /proc/mounts | awk '{print $2}'|sed 's/%/%%/g')\n"
        exit 0
        ;;
    esac
else
    case $1 in 
    find) my_dir=`ls -l /dev/disk/by-path/*usb* 2>/dev/null|sed 's%^.*/\([^/]*\)$%\1%'|fgrep -wf - /proc/mounts|cut -d' ' -f2|sed 's%\\\040% %g'|head -1`
        test -z "$my_dir" && exit 1
        echo "$my_dir"
        exit 0;;
    list) echo "USB_DISK"; exit 0;;
    esac
fi
#find_plist()
#{
#awk '
#BEGIN {
#    key=0
#}
#/'$1'/ {
#    key=1
#    next
#}
#{
#    if (key) {
#        sub("^.*<'$2'>","")
#        sub("</'$2'>.*$","")
#        print
#        key=0
#    } else
#        next
#}'
#}
#case $1 in
#list)
#mount|
#awk '
#/msdos/ {
#    print $1
#}
#!/msdos/ {
#    next
#}'|
#xargs -I% diskutil info -plist %|find_plist VolumeUUID string
#;;
#find)
#diskutil info -plist $2|find_plist MountPoint string
#;;
#esac
#case $1 in 
#find) my_dir=`mount|fgrep -w  msdosfs|sed -e 's/[^[:blank:]]*[[:blank:]]//; s/[^[:blank:]]*[[:blank:]]//; s/[[:blank:]]([^(]*)[^()]*$//g'|head -1`
#    test -z "$my_dir" && exit 1
#    echo "$my_dir/"
#    exit 0;;
#list) echo "USB_DISK";exit 0;;
#esac
#case $1 in 
#find) flash=''
#      for dev in `mount|awk '{print $3}'|grep ^/`; do
#        fs=`/usr/sbin/fstyp $dev 2>/dev/null` && test $fs = "pcfs" && flash=$dev
#      done
#      if [ -n "$flash" ]; then
#        mount| grep $flash |awk '{print $1}'
#        exit 0
#      fi
#;;
#list) echo "USB_DISK"; exit 0;;
#esac
