#!/bin/sh
# pocketds-mtp-sd-sync — mirror the (optional) microSD card into umtprd.
#
# The SD is a dynamic udisks mount under /run/media/<user>/<label> that
# only exists when a card is inserted AND a session mounted it, so it
# can't be a static umtprd.conf storage entry. Instead this script is
# run by umtp-responder.service at startup and by umtp-responder-sd.path
# on mount/unmount, and adds/removes an "SD Card" MTP storage at
# runtime. The microSD is the only mmcblk device on the Pocket DS
# (internal UFS storage shows up as sd*), so matching /dev/mmcblk* is
# device-accurate regardless of label or mountpoint.

set -u

STATE=/run/umtp-responder/sd-path

# "activating" must pass too: when run from ExecStartPost the start job
# isn't finished yet, so the unit is not "active" at that point.
case "$(systemctl show -P ActiveState umtp-responder.service)" in
    active|activating) ;;
    *) rm -f "$STATE"; exit 0 ;;
esac
mkdir -p /run/umtp-responder

# The path unit fires on the mountpoint mkdir; udisks mounts a moment
# later. Settle so findmnt sees the mount.
sleep 1

cur=$(awk '$1 ~ /^\/dev\/mmcblk/ {print $2; exit}' /proc/self/mounts \
      | sed 's/\\040/ /g; s/\\011/\t/g')
prev=$(cat "$STATE" 2>/dev/null || :)

[ "$cur" = "$prev" ] && exit 0

if [ -n "$prev" ]; then
    umtprd '-cmd:rmstorage:"SD Card"' || :
    rm -f "$STATE"
fi
if [ -n "$cur" ]; then
    umtprd "-cmd:addstorage:\"$cur\" \"SD Card\" rw,removable" \
        && printf '%s' "$cur" > "$STATE"
fi
exit 0
