Skip to content

Instantly share code, notes, and snippets.

@janw
Last active October 28, 2023 13:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save janw/af9506aa7fb8cb83a3c0349f2a793af1 to your computer and use it in GitHub Desktop.
Save janw/af9506aa7fb8cb83a3c0349f2a793af1 to your computer and use it in GitHub Desktop.
A simple molly-guard compatible script to request confirmation for rebooting a machine with active Plex sessions
#!/bin/sh
#
# 15-confirm-plex.sh - molly-guard script to request confirmation for rebooting
# a machine with active Plex sessions.
#
# To use it place the script in /etc/molly-guard/run.d/ and make it executable.
# Requires molly-guard, curl, jq:
#
# sudo apt install molly-guard curl jq
#
# Copyright © 2023 Jan Willhaus <mail@janwillhaus.de>
# Released under the terms of the Apache License, Version 2.0
#
set -eu
# Import settings if running molly-guard context
if [ -n "${MOLLYGUARD_SETTINGS:-}" ] && [ -f "$MOLLYGUARD_SETTINGS" ]; then
# shellcheck disable=SC1090
. "$MOLLYGUARD_SETTINGS"
fi
if [ -n "${PLEX_NO_CONFIRM:-}" ]; then
echo "I: molly-guard: No confirmation requested for Plex."
exit 0
fi
PLEX_AUTH_TOKEN="${PLEX_AUTH_TOKEN:-'place plex token here or in /etc/molly-guard/rc'}"
nc -z 127.0.0.1 32400 || exit 0 # Check if plex is running
test -t 0 || exit 0 # Check if shell is interactive
confirm() {
printf "Continue? [y/N]: "
IFS= read -r input || :
case $input in
[yY][eE][sS] | [yY])
return 0
;;
*)
return 1
;;
esac
}
sigh() {
echo "Good thing I asked; I won't $MOLLYGUARD_CMD …" >&2
exit 1
}
trap 'echo;sigh' HUP INT QUIT USR1 USR2 TERM
PLEX_SESSIONS=$(curl -SsfL \
--header "Accept: application/json" \
--header "X-Plex-Token: $PLEX_AUTH_TOKEN" \
'http://127.0.0.1:32400/status/sessions')
PLEX_ITEMS_PLAYING=$(echo "$PLEX_SESSIONS" | jq -r '.MediaContainer.size')
if [ "$PLEX_ITEMS_PLAYING" -eq 0 ]; then
exit 0
fi
echo "W: molly-guard: Plex has ${PLEX_ITEMS_PLAYING} active session(s)!" >&2
confirm || sigh
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment