#!/usr/bin/with-contenv bash

if grep -qs "PlexOnlineToken" "/config/Library/Application Support/Plex Media Server/Preferences.xml" || [ -z "$PLEX_CLAIM" ]; then
	exit 0
fi

if [ ! -f "/config/Library/Application Support/Plex Media Server/Preferences.xml" ]; then
	UMASK_SET=${UMASK_SET:-022}
	umask "$UMASK_SET"
	echo "Temporarily starting Plex Media Server."
	export PLEX_MEDIA_SERVER_INFO_MODEL=$(uname -m)
	export PLEX_MEDIA_SERVER_INFO_PLATFORM_VERSION=$(uname -r)
	s6-setuidgid abc /bin/bash -c \
		'LD_LIBRARY_PATH=/usr/lib/plexmediaserver:/usr/lib/plexmediaserver/lib /usr/lib/plexmediaserver/Plex\ Media\ Server' &
	echo "Waiting for Plex to generate its config"
	until grep -qs "ProcessedMachineIdentifier" "/config/Library/Application Support/Plex Media Server/Preferences.xml"; do
		sleep 1
	done
	echo "Stopping Plex to claim server"
	kill $(cat "/config/Library/Application Support/Plex Media Server/plexmediaserver.pid")
	wait
	echo "Plex stopped"
fi

ProcessedMachineIdentifier=$(sed -n "s/^.*ProcessedMachineIdentifier=\"\([^\"]*\)\".*$/\1/p" "/config/Library/Application Support/Plex Media Server/Preferences.xml")
PlexOnlineToken="$(curl -X POST \
	-H 'X-Plex-Client-Identifier: '"${ProcessedMachineIdentifier}" \
	-H 'X-Plex-Product: Plex Media Server'\
	-H 'X-Plex-Version: 1.1' \
	-H 'X-Plex-Provides: server' \
	-H 'X-Plex-Platform: Linux' \
	-H 'X-Plex-Platform-Version: 1.0' \
	-H 'X-Plex-Device-Name: PlexMediaServer' \
	-H 'X-Plex-Device: Linux' \
	"https://plex.tv/api/claim/exchange?token=${PLEX_CLAIM}" \
	| sed -n 's/.*<authentication-token>\(.*\)<\/authentication-token>.*/\1/p')"

if [ -n "$PlexOnlineToken" ]; then
	echo "Server claimed successfully, navigate to http://serverip:32400/web to complete plex setup."
	sed -i "s/\/>/ PlexOnlineToken=\"${PlexOnlineToken}\"\/>/g" "/config/Library/Application Support/Plex Media Server/Preferences.xml"
else
	echo "Unable to claim Plex server. Either manually claim by connecting to http://serverip:32400/web from the same network subnet, or recreate container with a new claim token."
fi