    elif command_exists lsb_release; then
      echo >> $FILE
      lsb_release -a 2> /dev/null | sed -e 's/^/    /' >> $FILE
-@@ -149,6 +153,28 @@ print_crash_report()
+@@ -149,6 +152,30 @@ print_crash_report()
    echo "Crash report available at $FILE"
  }
  
 +graceful_shutdown()
 +{
-+  echo "kodi.sh Warning: caught signal, attempting to kill Kodi gracefully" >&2
++  echo "kodi.sh: Warning: caught signal, attempting to kill Kodi gracefully" >&2
 +  $KODI_SEND --port=$KODI_SEND_PORT --action="Quit"
-+  if [ -n "$PID" ]; then
-+    local wait_time=10
-+    local wait_count=0
-+    while [ $wait_count -lt $wait_time ] && [ -e /proc/$PID ]; do
-+      retry_count=$(( $wait_count + 1 ))
++  if [ -n "$KODI_PID" ]; then
++    local wait_time=20
++    local retry_count=$wait_time
++    while [ $retry_count -gt 0 ] && [ -e /proc/$KODI_PID ]; do
++      retry_count=$(( $retry_count - 1 ))
 +      sleep 1
 +    done
-+    if [ -e /proc/$PID ]; then
-+      echo "kodi.sh Warning: PID $PID still running after $wait_time seconds" >&2
-+      kill -SIGTERM $PID
++    if [ -e /proc/$KODI_PID ]; then
++      echo "kodi.sh: Warning: KODI PID $KODI_PID still running after $wait_time seconds" >&2
++      echo "kodi.sh: Sending SIGTERM" >&2
++      kill -SIGTERM $KODI_PID
++      exit 23
++    else
++      exit 0
 +    fi
 +  fi
-+  rm -f $PIDFILE
-+  PID=
 +}
 +
 +trap graceful_shutdown SIGINT SIGTERM

From 78b41ba4efe56f19ccca1a5aee0d7254cdbf7285 Mon Sep 17 00:00:00 2001
From: Allen Wild <allenwild93@gmail.com>
Date: Mon, 15 May 2017 00:26:32 -0400
Subject: [PATCH] Graceful Shutdown Support

If running through systemd, combine this patch with KillMode=mixed
so only the wrapper script gets SIGTERM on service stop/restart.
---
 tools/Linux/kodi.sh.in | 38 +++++++++++++++++++++++++++++++++++---
 1 file changed, 35 insertions(+), 3 deletions(-)

diff --git a/tools/Linux/kodi.sh.in b/tools/Linux/kodi.sh.in
index 0a00a32034..d35ed7c3b0 100644
--- a/tools/Linux/kodi.sh.in
+++ b/tools/Linux/kodi.sh.in
@@ -28,6 +28,9 @@ LIBDIR="@libdir@"
 CRASHLOG_DIR=${CRASHLOG_DIR:-$HOME}
 USERDATA_DIR="${HOME}/.${bin_name}"
 
+KODI_SEND="@bindir@/kodi-send"
+KODI_SEND_PORT=9777
+
 
 # Workaround for high CPU load with nvidia GFX
 export __GL_YIELD=USLEEP
@@ -94,8 +97,8 @@ print_crash_report()
   uname -rvs >> $FILE
   printf " Release: " >> $FILE
   if [ -f /etc/os-release ]; then
