#!/bin/sh
# mtp_download.sh
# 2024-09-22
# by Gernot Walzl
if [ -r "$HOME/.config/user-dirs.dirs" ]; then
. "$HOME/.config/user-dirs.dirs"
fi
PICTURES_DIR=${XDG_PICTURES_DIR:-$HOME/Pictures}
VIDEOS_DIR=${XDG_VIDEOS_DIR:-$HOME/Videos}
TMP=${TMP:-/tmp}
read_model () {
LANG=C mtp-detect 2> /dev/null \
| sed -n '/Model:/ s/.*Model: // p' \
| sed 's#[/ ]#_#g'
}
wait_for_mtp () {
local CNT=0
while [ -z "$(read_model)" ]; do
/bin/echo -ne "\rWaiting for mtp-detect ... $CNT"
sleep 1
CNT=$(($CNT + 1))
done
/bin/echo ''
}
download () {
local FILEEXT="$1"
local DESTMODELDIR="$2"
if [ -z "$FILEEXT" -o -z "$DESTMODELDIR" ]; then
return 1
fi
mkdir -p "$TMP/mtp"
jmtpfs "$TMP/mtp" || return 1
find "$TMP/mtp" -type f -iname "*.$FILEEXT" \
| while read FILE; do
DATE=$(stat -c %y "$FILE" | cut -d' ' -f1)
if [ "$FILEEXT" = "jpg" -a "$3" = "exif" ]; then
EXIFDATE=$(exiv2 -g Exif.Image.DateTime -Pv "$FILE" | cut -d' ' -f1 | sed 's/:/-/g')
if [ -n "$EXIFDATE" ]; then
DATE=$EXIFDATE
fi
fi
mkdir -p "$DESTMODELDIR/$DATE"
cp -pv "$FILE" "$DESTMODELDIR/$DATE"
done
fusermount -u "$TMP/mtp"
rmdir "$TMP/mtp"
}
wait_for_mtp
MODEL=$(read_model)
if [ -n "$MODEL" ]; then
if [ -z "$1" ]; then
download "jpg" "$PICTURES_DIR/$MODEL"
download "heic" "$PICTURES_DIR/$MODEL"
download "mp4" "$VIDEOS_DIR/$MODEL"
elif [ -n "$2" ]; then
download "$1" "$2/$MODEL" "$3"
fi
fi