Skip to content

Instantly share code, notes, and snippets.

@aarmot
Last active Dec 16, 2015
Embed
What would you like to do?
Hotplug2 script to automatically start minidlna every time the USB disk gets attached and stop minidlna when disk gets detached. Configuration parameters are at the top of script.
#!/bin/sh
# Hotlug2 script which starts minidlna when USB disk gets attached
# aarmot@gmail.com
# Sharing: GPLv3 or later
# To handle minidlna startup through hotplug you should disable minidlna autostart
# /etc/init.d/minidlna disable
# and copy current script to /etc/hotplug.d/block/30-minidlna
# Minimum size (in GB) of disk where minidlna database can be mounted
# This check tries to avoid writing temporal data to USB flash drives
MINIDLNA_USE_DISK=100
# Subdirectory for minidlna DB
MINIDLNA_DIR=.minidlna
# If "1" then minidlna database gets rebuilt from scratch after each mount
MINIDLNA_FORCE_REBUILD=1
# If "1" then swap is unmounted after minidlna DB has been rebuilt
MINIDLNA_RELEASE_SWAP=1
# Script works only on devices sda .. sdh
[ -z "$DEVNAME" -o -n "${DEVNAME#sd[a-h]}" ] && exit 0
start_minidlna() {
local d
rm -rf /var/run/minidlna
if [ $(cat /sys/block/$DEVNAME/size) -gt $(($MINIDLNA_USE_DISK*2048000)) ]; then
d=$(grep ^/dev/$DEVNAME /proc/mounts | head -1 | cut -d ' ' -f 2)
if [ -n "$d" ]; then
mkdir -m 0755 -p $d/$MINIDLNA_DIR
[ "$MINIDLNA_FORCE_REBUILD" = 1 ] && rm -rf $d/$MINIDLNA_DIR/*
ln -s $d/$MINIDLNA_DIR /var/run/minidlna
[ -f $d/.swap ] && swapon $d/.swap
fi
fi
rm -f /var/log/minidlna.log
/etc/init.d/minidlna restart
if [ "$MINIDLNA_RELEASE_SWAP" = 1 -a $(cat /proc/swaps | wc -l) -gt 1 ]; then
sleep 120
while [ $(ps | grep '[m]inidlna' | wc -l) -gt 1 ]; do
sleep 60
done
swapoff -a
fi
}
stop_minidlna() {
/etc/init.d/minidlna stop
rm -rf /var/run/minidlna
sleep 10
d=$(grep /dev/$DEVNAME /proc/mounts | cut -d ' ' -f 2)
[ -n "$d" ] && umount $d
}
L=/tmp/.mntsrv.lock
case "$ACTION" in
add)
if ln -s . $L; then (
sleep 5
start_minidlna
rm -f "$L"
) &
fi
;;
remove)
if ln -s . $L; then (
stop_minidlna
sleep 1
rm -f "$L"
) &
fi
;;
esac
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment