#!/bin/sh
# Start-Stop-Status - DSM 7

# Path to this script
ScriptDir="$(dirname "$0")"

# Message text handler function
# Simple function to keep code clean and pass mneumonic code and arguments to message-text script
MessageText(){
  "$ScriptDir/message-text" "$1" "$2" "$3" "$4"
}


# Service variables
PlexPkgShare="/var/packages/PlexMediaServer/shares/PlexMediaServer"
PlexPkgHome="$PlexPkgShare/AppData"
PID_FILE="$PlexPkgHome/plexmediaserver.pid"

# DSM version variables
DSM_VERSION="$(get_key_value /etc.defaults/VERSION productversion)"
DSM_BUILD="$(get_key_value /etc.defaults/VERSION buildnumber)"
DSM_UPDATE="$(get_key_value /etc.defaults/VERSION smallfixnumber)"

# Identification variables
PMS_INFO_VENDOR="Synology"
PMS_INFO_DEVICE="$(get_key_value /etc.defaults/synoinfo.conf unique|cut -d'_' -f3|sed 's/^ds/DS/;s/^fs/FS/;s/^rs/RS/'|sed 's/^\([0-9]\)/DS\1/')"
PMS_INFO_MODEL="$(uname -m)"
PMS_INFO_PLATFORM_VERSION="DSM $DSM_VERSION.$DSM_BUILD-$DSM_UPDATE"


server_start ()
{

  # Verify my Identity
  [ "$(whoami)" != "PlexMediaServer" ] && exit 1

  # Kill any residual processes which DSM did not clean up (plug-ins and EAE)
  Pids="$(ps -ef | grep -i 'plex plug-in' | grep -v grep | awk '{print $2}')"
  [ "$Pids" != "" ] && kill -9 $Pids

  Pids="$(ps -ef | grep -i 'plex eae service' | grep -v grep | awk '{print $2}')"
  [ "$Pids" != "" ] && kill -9 $Pids

  # Give sockets a moment to close
  sleep 2

  # Set LANG & LC_ALL only if not UTF-8 or UTF-16 otherwise trust host region setting.
  LANG="$(echo $LANG | sed -e 's/[Uu][Tt][Ff]-*8/UTF-8/')"
  LANG="$(echo $LANG | sed -e 's/[Uu][Tt][Ff]-*16/UTF-16/')"

  LC_ALL="$(echo $LC_ALL | sed -e 's/[Uu][Tt][Ff]-*8/UTF-8/')"
  LC_ALL="$(echo $LC_ALL | sed -e 's/[Uu][Tt][Ff]-*16/UTF-16/')"

  [ ! $(echo $LANG   | grep UTF-8 ) ] && [ ! $(echo $LANG   | grep UTF-16) ] && export LANG=en_US.UTF-8
  [ ! $(echo $LC_ALL | grep UTF-8 ) ] && [ ! $(echo $LC_ALL | grep UTF-16) ] && export LC_ALL=en_US.UTF-8

  # Silently create tmp dir in case was deleted
  mkdir -p "$PlexPkgHome/tmp"

  # Set service environment
  export SYSCALL_MAX_ENABLED=1
  export PLEX_MEDIA_SERVER_MAX_PLUGIN_PROCS=6
  export PLEX_MEDIA_SERVER_APPLICATION_SUPPORT_DIR="$PlexPkgHome"
  export PLEX_MEDIA_SERVER_DEFAULT_PREFERENCES='HardwareAcceleratedCodecs=true&TranscoderCanOnlyRemuxVideo=false'
  export PLEX_MEDIA_SERVER_INFO_VENDOR="$PMS_INFO_VENDOR"
  export PLEX_MEDIA_SERVER_INFO_DEVICE="$PMS_INFO_DEVICE"
  export PLEX_MEDIA_SERVER_INFO_MODEL="$PMS_INFO_MODEL"
  export PLEX_MEDIA_SERVER_INFO_PLATFORM_VERSION="$PMS_INFO_PLATFORM_VERSION"
  export PLEX_MEDIA_SERVER_PIDFILE=$PID_FILE
  export PLEX_BROWSER_NO_HOME_DIR=1
  export TMPDIR="$PlexPkgHome/tmp"
  ulimit -s 3000

  # Spawn service binary
  "$SYNOPKG_PKGDEST/Plex Media Server" >> /dev/null 2>&1 &

  # Wait for service status
  wait_for_status 0

  # Verify server status
  server_status
  return $?
}

server_stop ()
{
  if [ -r "$PID_FILE" ]; then
    PID=$(cat "$PID_FILE")

    kill -TERM "$PID" >> /dev/null 2>&1
    wait_for_status 1 || kill -KILL "$PID" >> /dev/null 2>&1

    [ -f "$PID_FILE" ] && rm -f "$PID_FILE" >> /dev/null 2>&1
  fi

  return 0

  # PMS has been asked nicely to shut down, now verify.
  Pids="$(ps -ef | grep Plex | awk '{print $2}')"

  Count=10
  Sig=-9

  while [ "$Pids" != "" ] && [ $Count -gt 0 ]
  do
    # Kill what's still running
    kill $Sig $Pids
    sleep 5

    # Look again
    Pids="$(ps -ef | grep Plex | awk '{print $2}')"
    Count=$(($Count -1))

    # Force them down if our last iteration
    if [ $Count -eq 1 ]; then
    Sig=-11
    fi
  done
  return 0
}

server_status ()
{
  # If no PID file, it's stopped (1)
  [ ! -f "$PID_FILE" ] && return 1

  # Return true (0) if valid PID file exists
  Pid="$(cat "$PID_FILE")"
  [ "$Pid" != "" ] && [ -d /proc/$Pid ] && return 0

  # The PID file is pointing off to something bad. (implied stopped state). Clean
  rm -f "$PID_FILE"
  return 1
}

wait_for_status ()
{
  counter=20 # 20 seconds
  while [ ${counter} -gt 0 ]; do
    server_status
    [ $? -eq "$1" ] && return
    counter=$((counter-1))
    sleep 1
  done
  return 1
}

case $1 in
  start)
    if server_status; then
      echo "Plex Media Server is already running"
      exit 0
    else
      echo "Starting Plex Media Server ..."
      server_start
      exit 0
    fi
    ;;

  stop)
    if server_status; then
      echo "Stopping Plex Media Server ..."
      server_stop
      exit 0
    else
      echo "Plex Media Server is not running"
      exit 0
    fi
    ;;

  status)
    if server_status; then
      echo "Plex Media Server is running"
      exit 0
    else
      echo "Plex Media Server is not running"
      exit 3
    fi
    ;;
  *)
    exit 1
    ;;
esac
