#!/bin/dash
# originally written by 01micko, http://murga-linux.com/puppy/viewtopic.php?p=839972#839972
# re-written by jamesbond 2015
# License: MIT License
#

### config
APPTITLE="MTP Browser"

### helper
dlg() {
	Xdialog --stdout --title "$APPTITLE" "$@"
}

msg() {
	dlg --msgbox "$*" 0 0 
}

info() {
	dlg --infobox "$*" 0 0 10000
}

# in: $1-devices $2-selected out: $devno
count() {
	devno=1
	for p in $1; do
		[ $p = $2 ] && return
		: $((devno=devno+1))
	done
	devno=""
}

### main
msg "Please plug-in your device now.
Click OK when ready."

DEVICES=$(simple-mtpfs-detect | awk '$1 ~ /[0-9]+:/ { print $4 }')
if [ -z "$DEVICES" ]; then
	info "No MTP devices found."
	exit
fi

MODELS=""
for p in $DEVICES; do
	MODELS="$MODELS $(udevadm info --query=property --name=/dev/bus/usb/${p%:*}/${p#*:} | 
	        sed '/ID_MODEL=/!d; s/ID_MODEL=//' | tr "'\\/ .;:?*[](){}\t" _ )"
done

for p in $MODELS; do
	pp="$pp '$p' '$p'"
done

if dev=$(eval dlg --no-tags --menubox "'Choose device to connect'" 15 60 3 $pp); 
then
	count "$MODELS" $dev
	if [ -z $devno ]; then
		info "Unknown error."
		exit
	fi

	mntpoint=$HOME/mtp_$dev
	echo $mntpoint
	mkdir -p $mntpoint
	simple-mtpfs --device $devno $mntpoint
	rox -d $mntpoint
	info "\
Don't forget to umount it before disconnecting your device.

You can do that by going to your $HOME folder, find the mtp_* folder 
with a green dot on it, right-click on it and then choose \"User Unmount\".

Or from terminal you can type: 
\"fusermount -u $mntpoint\"
"	
else
	info "Cancelled. Nothing is changed."
fi

