#!/bin/sh
# Start/stop/restart the jellyfin server :

start() {
	if killall -0 jellyfin 2>/dev/null ; then
		echo "jellyfin already started ..."
	else
		echo "Starting jellyfin ..."
		
		# Program directories
		export JELLYFIN_DATA_DIR="$HOME/.cache/jellyfin"
		export JELLYFIN_CONFIG_DIR="$HOME/.config/jellyfin"
		export JELLYFIN_LOG_DIR="$HOME/.cache/jellyfin"
		export JELLYFIN_CACHE_DIR="$HOME/.cache/jellyfin"
		export JELLYFIN_WEB_DIR="/usr/share/jellyfin/web"
		export JELLYFIN_RESTART_SCRIPT="/usr/lib64/jellyfin/restart.sh"
		
		mkdir -p $JELLYFIN_DATA_DIR $JELLYFIN_CONFIG_DIR $JELLYFIN_LOG_DIR $JELLYFIN_CACHE_DIR $JELLYFIN_WEB_DIR
		
		# Restart script for in-app server control
		export JELLYFIN_RESTART_OPT="--restartpath=$JELLYFIN_RESTART_SCRIPT"

		# ffmpeg binary paths, overriding the system values
		# JELLYFIN_FFMPEG_OPT="--ffmpeg=/usr/lib64/jellyfin-ffmpeg/ffmpeg"

		# [OPTIONAL] run Jellyfin as a headless service
		# export JELLYFIN_SERVICE_OPT="--service"

		# [OPTIONAL] run Jellyfin with(out) the web app
		export JELLYFIN_WEB_OPT="--webdir=$JELLYFIN_WEB_DIR"
		# export JELLYFIN_NOWEBAPP_OPT="--nowebclient"

		# [OPTIONAL] run Jellyfin with ASP.NET Server Garbage Collection (uses more RAM and less CPU than Workstation GC)
		# 0 = Workstation
		# 1 = Server
		export COMPlus_gcServer=1
		
		# Start
    while [ "$(hostname -I)" == "" ]; do sleep 1 ; done
    /usr/lib64/jellyfin/bin/jellyfin $JELLYFIN_RESTART_OPT $JELLYFIN_WEB_OPT $JELLYFIN_SERVICE_OPT $JELLYFIN_NOWEBAPP_OPT $JELLYFIN_FFMPEG_OPT &
	fi
}

stop() {
	
	if killall -0 jellyfin 2>/dev/null ; then
		echo "Stoping jellyfin ..."
		killall -15 jellyfin 2>/dev/null
		sleep 2
		killall -9 jellyfin 2>/dev/null
	else
		echo "jellyfin already stoped ..."
	fi
}

case "$1" in
'start')
  while [ "$(hostname -I)" = "" ]; do sleep 1 ; done
	start
	;;
'stop')
	stop
	;;
'restart')
	stop
	start
	;;
*)
	echo "usage : $0 start|stop|restart"
esac

